C#控制台遍历列表输出Program+SqlObject而非对象值问题
解决方法
问题根源
直接打印SqlObject实例时,C#默认调用基类ValueType的ToString()方法,返回类型的完整名称(即你看到的Program+SqlObject),而非对象属性值。
方案1:重写SqlObject的ToString()方法
修改结构体,添加自定义ToString()实现,打印对象时自动输出目标格式:
struct SqlObject { public int id { get; set; } public string date { get; set; } public int quantity { get; set; } // 重写ToString方法 public override string ToString() { return $"id:{id}, date:{date}, Quantity:{quantity}"; } }
方案2:手动输出对象属性
若不想重写方法,遍历直接指定输出属性:
// 替换ViewDates里的sqlList.ForEach行 sqlList.ForEach(i => Console.WriteLine($"id:{i.id}, date:{i.date}, Quantity:{i.quantity}"));
额外优化:修复ViewDates的列表使用问题
当前ViewDates每次读取数据都新建List,效率低下,可直接打印当前对象:
void ViewDates() { using (var connection = new SqliteConnection(@"Data Source=C:\Databases\HabitTrackerV3.db")) { connection.Open(); Console.WriteLine("Ran"); var command = connection.CreateCommand(); command.CommandText = "SELECT * FROM drinking_water "; using (var reader = command.ExecuteReader()) { Console.WriteLine("looped"); int index = 0; while (reader.Read()) { int id = reader.GetInt32(0); string Date = reader.GetString(1); int Quantity = reader.GetInt32(2); var sqlObj = new SqlObject {id = id, date = Date, quantity = Quantity}; // 带索引打印 Console.WriteLine($"{index}: {sqlObj}"); index++; } } connection.Close(); } }
重要提示:避免SQL注入
当前AddDate用字符串拼接生成SQL,存在注入风险,改用参数化查询:
void AddDate() { DateInputCommand(); using (var connection = new SqliteConnection(@"Data Source=C:\Databases\HabitTrackerV3.db")) { connection.Open(); var command = connection.CreateCommand(); command.CommandText = "INSERT INTO drinking_water(date,Quantity) VALUES(@date, @quantity)"; command.Parameters.AddWithValue("@date", globalDateInput); command.Parameters.AddWithValue("@quantity", globalQuantityInput); command.ExecuteNonQuery(); connection.Close(); } }
内容的提问来源于stack exchange,提问作者Josh knon
相关产品推荐
相关产品推荐

