gpt4 book ai didi

c# - OleDB/MySQL参数添加

转载 作者:行者123 更新时间:2023-11-29 11:56:36 26 4
gpt4 key购买 nike

我有一个关于向命令(MySQL 或 OleDB,我目前使用这两者)添加参数以避免 SQL 注入(inject)的问题。

除了开放的注入(inject)漏洞之外,这个硬编码查询工作得绝对正常;

var queryString = string.Format("SELECT COUNT(*) FROM employs WHERE em_netname = '"+username+"' AND em_password = '"+password+"'");

但是,在修改查询以添加参数而不是让漏洞保持打开状态后,它不起作用。我就是这样做的;

var queryString = string.Format("SELECT COUNT(*) FROM employs WHERE em_netname = @username AND em_password = @password");
OleDbCommand dbfQuery = new OleDbCommand(queryString, dbfCon);
dbfQuery.Parameters.Add("@username", OleDbType.Char).Value = username;
dbfQuery.Parameters.Add("@password", OleDbType.Char).Value = password;

有人可以给我解释一下为什么这不起作用吗?第一个查询从 count 返回 1,第二个查询返回 0(它应该返回 1)。

编辑:为了清楚起见,“不起作用”我的意思是第一个语句返回列计数 1,即有一个用户,查询确实有效。第二条语句输入完全相同的用户名和密码,返回 0,即尽管确实存在用户名和密码组合(由第一条语句证明),但查询无法正常工作。

编辑2:发布整个类代码;

public static bool AuthenticateUser(string username, string password)
{
var constr = ConfigurationManager.ConnectionStrings["dbfString"].ConnectionString;
using (OleDbConnection dbfCon = new OleDbConnection(constr))
{
try
{
dbfCon.Open();
var queryString = string.Format("SELECT COUNT(*) FROM employs WHERE em_netname = @username AND em_password = @password");
OleDbCommand dbfQuery = new OleDbCommand(queryString, dbfCon);
dbfQuery.Parameters.Add("@username", OleDbType.Char).Value = username;
dbfQuery.Parameters.Add("@password", OleDbType.Char).Value = password;
MessageBox.Show("Query: " + queryString);
int numOfColumns = Convert.ToInt32(dbfQuery.ExecuteScalar());
MessageBox.Show(numOfColumns.ToString());
if (numOfColumns == 1)
{
return true;
}
else
{
return false;
}
}
catch (OleDbException)
{
throw;
}
}
}

最佳答案

根据MSDN OleDbCommand 不支持命名参数。尝试使用 ? 代替。

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:

SELECT * FROM Customers WHERE CustomerID = ?

Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

关于c# - OleDB/MySQL参数添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33097466/

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