首页 > 解决方案 > 如何将从数据库检索到的 int 转换为字符串

问题描述

我有一个登录表单,我想从数据库userID中选择(形式为 an 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'类型。

标签: c#sql

解决方案


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

// 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
  }
}

推荐阅读