我有一个登录表单,想要从数据库中选择userID
(形式为int
),并将其存储为string
。
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:'无法转换类型的对象 “ System.Int32”键入“ System.String”。
答案 0 :(得分:8)
如果记录不存在(即光标为 empty )怎么办?让我们阅读并检查是否至少有一条记录:
// 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
}
}
答案 1 :(得分:3)
您可以尝试如下使用
string result = Convert.ToString(com.ExecuteScalar());
答案 2 :(得分:1)
最简单的解决方案可能是(假设查询始终返回结果):
string result = com.ExecuteScalar().ToString();
您还可以在查询中将其转换为nvarchar:
string insertQuery = "SELECT cast(UserID as nvarchar) FROM Customers WHERE Email = @Email AND Password = @Password";
答案 3 :(得分:1)
ExecuteScalar返回对象类型,您可以将其转换为所需的任何类型
public override object ExecuteScalar ();
您可以调用它的ToString()方法,并返回其值的字符串形式。
答案 4 :(得分:1)
尝试一下
string result = string.Empty;
SqlCommand com = new SqlCommand(..);
..
object executedResult = com.ExecuteScalar();
if(executedResult != null) {
result = executedResult.ToString();
}
希望有帮助,
答案 5 :(得分:0)
下面是我的发现
string userID;
using(SqlConnection conn = new SqlConnection(connectionString))
{
string insertQuery = "SELECT UserID FROM Customers WHERE Email = @Email AND
Password = @Password";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("@Email", tbEmail.Text.ToString().Trim());
com.Parameters.AddWithValue("@Password", tbPassword.Text.ToString().Trim());
SqlDataReader reader = com.ExecuteReader();
while(reader.Read())
{
userID = reader["UserID"].ToString();
}
}