我正在尝试从 C# WinForms 程序连接到 mysql。一切似乎都工作正常,我得到了 99% 的列值,只是一个 int
列不想返回正确的值:
public static void getFromMySqlAndInsertIntoSql() {
const string preparedCommand = @"
select *
from agreements";
using (var varConnection = Locale.sqlConnectOneTimeMySql(Locale.sqlDataConnectionDetailsMySQL))
using (var sqlQuery = new MySqlCommand(preparedCommand, varConnection)) {
using (var sqlQueryResult = sqlQuery.ExecuteReader())
while (sqlQueryResult.Read()) {
int agr_id = sqlQueryResult["agr_id"] is int ? (int)sqlQueryResult["agr_id"] : int.MinValue;
string agr_idTest = sqlQueryResult["agr_id"].ToString();
string agr_fname = sqlQueryResult["agr_fname"].ToString();
int agr_stocks_count = sqlQueryResult["agr_stocks_count"] is int ? (int)sqlQueryResult["agr_stocks_count"] : int.MinValue;
MessageBox.Show(agr_id.ToString(), agr_idTest);
}
}
}
}
agr_id
始终返回 int.MinValue,但 agr_idTest
它返回正确的字符串。 agr_stocks_count
的 int
值正确返回 int,因此这似乎不是代码的问题。
我在 MySQL 表中可以找到的第一个 int 列和另一个之间的唯一区别是:
Field Type Collation Attributes Null Default Extra
agr_id int(10) UNSIGNED No None AUTO_INCREMENT
agr_stocks_count int(11) No None
有没有人解释一下?
最佳答案
DB 上的 int(10) 不会映射到 C# 中的 int。不要使用 is int
,而是尝试使用 System.Convert
。
即使用:
int agr_id = System.Convert.ToInt32(sqlQueryResult["agr_id"]);
关于c# - 在 C# 中读取 MySQL Int(10) 值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5126588/