标准表达式c#access中的数据类型不匹配 [英] data type mismatch in criteria expression c# access
问题描述
我正在尝试从表用户中选择usercod
usercod数据类型是数字
C#程序连接到MS Access。以下是代码
//错误显示在这里
I'm trying to select usercod from table users
usercod datatype is Number
C# program connecting to the MS Access. Here are the codes
//the error show here
public int GetUserIdAfterLogin(string strUserName, string strPassword)
{
int inUserId = 0;
try
{
if (oldbcon.State == ConnectionState.Closed)
{
oldbcon.Open();
}
string select = "select usercod from users where Username='" + strUserName + "' and userpassword='" + strPassword + "'";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oldbcon;
cmd.CommandText = select;
inUserId = Convert.ToInt32(cmd.ExecuteScalar().ToString());
}
catch (Exception ex)
{
MessageBox.Show("USP:2" + ex.Message, "my form", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
oldbcon.Close();
}
return inUserId;
}
谢谢
Thanks
推荐答案
两点.. 。
1.请参阅@digimanus的评论。无需尝试ToString
和转换
。只需使用
Two points...
1. See the comment from @digimanus. There is no need to attempt aToString
and aConvert
. Just use
inUserId = (Int32)cmd.ExecuteScalar();
(万一你遇到类型不匹配或非法转换,然后声明变量,因此 Int32 inUserId = 0;
)
2.最重要的一点 - 永远不要使用连接字符串来形成sql查询。您将自己置于 SQL注入的风险之中[ ^ ]。请改用参数化查询。还有其他好处 - 尤其是不必担心字符串和日期周围的单引号。
例如
(In the unlikely event you get a type mismatch or illegal cast then declare the variable thus Int32 inUserId = 0;
)
2. The most important point - never, ever, use concatenated strings to form sql queries. You put yourself at risk of SQL Injection[^]. Use parameterised queries instead. There are other benefits to this - not least not having to worry about single quotes around strings and dates.
E.g.
string select = "select usercod from users where Username= @strUserName and userpassword=@strPassword ";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oldbcon;
cmd.CommandText = select;
cmd.Parameters.AddWithValue("@UserName", strUserName);
cmd.Parameters.AddWithValue("@strPassword", strPassword);
inUserId = (Int32) cmd.ExecuteScalar();
这篇关于标准表达式c#access中的数据类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!