C
C#3mo ago
DJBonez

C# MySQL Windows form application

To preface this question I am learning development in C# on my own, no classes or formal training. I am writing a very simple app to get familiarized with windows forms and databases. I have a working app, however; if I want to add a new field in the database, then go to the class where I list all my fields with public string or int. Then go to the DAO I created, where have it reading the table. I always get NULL issue, if I back out the new field in all the locations everything works again. Sample of the class namespace csapp public class Customers { public int CustomerID { get; set; } public string? BusinessName { get; set; } public string? LastName { get; set; } public string? FirstName { get; set; }.... addition when it breaks public string? OtherPhone {get;set;} Sample of the DAO file internal class csappDAO { string connectionString = "datasource=localhost;port=3306;username=admin;password=admin;database=csappdb;";
public List<Customers> getAllCustomers() { // start with an empty list List<Customers> returnThese = new List<Customers>(); // connect to the mysql server MySqlConnection connection = new MySqlConnection(connectionString); connection.Open(); // define the sql statement to fetch all customers MySqlCommand command = new MySqlCommand("SELECT * FROM customers", connection); using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Customers a = new Customers { CustomerID = reader.GetInt32(0), BusinessName = reader.GetString(1), LastName = reader.GetString(2), FirstName = reader.GetString(3),... addition when it breaks OtherPhone=reader.GetString(21) Hopefully this makes since
8 Replies
Keswiik
Keswiik3mo ago
First off, have you verified that your new column is present in your database schema?
DJBonez
DJBonez3mo ago
Yes, I have created in the database first
DJBonez
DJBonez3mo ago
This is the error I get when ever I want to add something new.
No description
Keswiik
Keswiik3mo ago
might need to check if the column is null before attempting to read the value although I haven't worked with raw SQL very often in c#
Pobiega
Pobiega3mo ago
Never use SELECT * in a programmatic query Name and order each field. Use parameterized queries, and consider using Dapper instead of raw ADO
DJBonez
DJBonez3mo ago
Pobiega, thanks for the advice. Even though this is not a "web app" should I still use parameterized queries? I will try and learn Dapper as it seems from my small amount of research, is a better way of accessing data.
Pobiega
Pobiega3mo ago
Yeah, always use parameterized queries. Its one extra line of code when using dapper, and one extra line per parameter when using raw ADO.NET its well worth the "effort" to do things properly