gpt4 book ai didi

c# - 我如何将从数据库中检索到的 int 转换为字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:16:46 24 4
gpt4 key购买 nike

我有一个登录表单,我想从数据库中选择 userID(以 int 的形式),并将其存储为 字符串.

string insertQuery = 
"SELECT UserID FROM Customers WHERE Email = @Email AND Password = @Password";

SqlCommand com = new SqlCommand(insertQuery, conn);

com.Parameters.AddWithValue("@Email", tbEmail.Text);
com.Parameters.AddWithValue("@Password", tbPassword.Text);

string result = (string)com.ExecuteScalar();

但是在我登录之后,我得到了这个错误:

System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'.

最佳答案

如果记录不存在(即光标)怎么办?让我们阅读并检查我们是否至少有一条记录:

// Keep Sql being readable
string insertQuery =
@"SELECT UserID
FROM Customers
WHERE Email = @Email
AND Password = @Password";

// Do not forget to dispose IDisposable
using (SqlCommand com = new SqlCommand(insertQuery, conn)) {
com.Parameters.AddWithValue("@Email", tbEmail.Text);
com.Parameters.AddWithValue("@Password", tbPassword.Text);

using (var reader = com.ExecuteReader()) {
string result = reader.Read()
? Convert.ToString(reader[0]) // record exists
: null; // cursor is empty

//TODO: put relevant code which works with result here
}
}

关于c# - 我如何将从数据库中检索到的 int 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53958845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com