c# - 如何将从数据库检索到的 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'类型。
解决方案
如果记录不存在(即光标为空)怎么办?让我们阅读并检查我们是否至少有一条记录:
// 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
}
}
推荐阅读
- r - 在ggplot2中添加手动设计的非线性线?
- python - “KMeans”对象没有属性“k”
- sql - ORACLE SQL:将从零开始的 NUMBER 转换为 XML 时出现问题
- javascript - 如何在 PHP 中为链接使用 JS 属性?
- xamarin.forms - Xamarin forms 5.0 CollectionView 拖动外观多个项目
- javascript - 如何为边框设置动画,使其从头到尾缓慢显示
- phpstorm - PhpStorm - 放大非编辑器文本(例如菜单和工具窗口)
- django - 在 plotly dash 和 django 视图之间共享数据
- javascript - 异步函数应仅更新一项时覆盖数组状态
- python - Python 中的快速流线图