我有一个我正在使用的简单数据库。它包含两个用户条目,即UserID为1和IsAdmin为0的用户,另一个用户ID为3041234567,IsAdmin为1.数据库中的唯一字段是字符串UserID和位IsAdmin。我正在使用以下代码从数据库中读取:
SqlConnection conn = new SqlConnection(Properties.Settings.Default.Conn);
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE UserID = " + t.Text.ToString(), conn);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
user.UserID = reader["UserID"].ToString();
user.IsAdmin = Convert.ToBoolean(reader["IsAdmin"]);
}
}
conn.Close();
如果我输入数字3041234567作为UserID一切正常,但如果我输入数字1,我会得到一个例外,说明" nvarchar值的转换' 3041234567'溢出了一个int列。"
如果我设置断点并观察while(reader.read())循环,则循环遍历精细并设置user.UserID = 1和user.IsAdmin = false。循环开始迭代第二次时抛出异常。我想我有几个问题:
"SELECT * FROM Users WHERE UserID = 1"
答案 0 :(得分:4)
好吧,因为
3041234567 > int.MaxValue ( == 2147483647)
您有溢出;但是,如果你想要某种整数值,请尝试long
(64位长):
long value = Convert.ToInt64(reader["UserID"]);
这样的事情:
// Wrap IDisposable into using
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.Conn)) {
conn.Open();
// Make sql
// 1. Readable
// 2. Parametrized
// 3. Avoid * in select
String sql =
@"select UserID,
IsAdmin
from Users
where UserID = @prm_UserId";
// Wrap IDisposable into using
using (SqlCommand cmd = new SqlCommand(sql, conn)) {
// Explicit data type will be better here (Add Parameter with type)
// but I don't know it
cmd.Parameters.AddWidthValue("prm_UserId", t.Text);
// Wrap IDisposable into using
using (SqlDataReader reader = cmd.ExecuteReader()) {
// You don't want to iterate the whole cursor, but the first record
if (reader.Read()) {
//TODO: Make UserID being "long"
user.UserID = Convert.ToInt64(reader["UserID"]);
user.IsAdmin = Convert.ToBoolean(reader["IsAdmin"]);
}
}
}
}