再次给出插入查询的语法错误

时间:2010-07-31 06:06:48

标签: c#

string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Samples\\login.mdb";
string uname, pass;
uname = textBox1.Text;
pass = textBox2.Text; 

OleDbConnection myConnection = new OleDbConnection(connectionString);
myConnection.Open();

string query = "insert into LOGIN_TABLE (UserName, Password) VALUES ('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "') ";

OleDbCommand myCommand = new OleDbCommand(query, myConnection);
//myCommand.CommandText = query;
OleDbParameter myParm = myCommand.Parameters.Add("@uname", OleDbType.VarChar, 50);
myParm.Value = textBox1.Text;

myParm = myCommand.Parameters.Add("@pass", OleDbType.VarChar, 50);
myParm.Value = textBox2.Text;

myCommand.ExecuteNonQuery();
myConnection.Close();

3 个答案:

答案 0 :(得分:4)

来自OleDbCommand.Parameters的文档:

  

OLE DB .NET提供程序没有   支持传递的命名参数   SQL语句或参数的参数   由...调用的存储过程   设置CommandType时的OleDbCommand   到文本。在这种情况下,问题   必须使用mark(?)占位符。

在同一页面上有一个例子。

但是,您甚至没有在SQL查询中使用参数。您通过将用户输入直接嵌入到SQL中然后添加参数来邀请SQL注入攻击。

您的查询应该是:

String query = "insert into LOGIN_TABLE (UserName, Password) VALUES (?, ?)";

看起来可以仍然提供参数名称,即使它们没有被使用 - 所以只需更改上面的内容即可。

编辑:用户名或密码是否可能是保留名称?尝试转义它们 - 我知道在SQL Server中它将是[UserName], [Password]但我不知道在Access中是否属实。如果您尝试在Access中执行相同的SQL,会发生什么?

答案 1 :(得分:-1)

您作为参数传递的数据可能包含单引号'。 在为参数赋值时,请尝试使用此文本Box2.Text.Replace(“'”,“''”)。

还有一件事,在简单查询中处理简单文本和数字时没有必要使用参数。

答案 2 :(得分:-1)

您的查询应该是这样的。

string query = "insert into LOGIN_TABLE (UserName, Password) VALUES ( @uname, @pass )";

现在写完你的代码后,一切都会对你有用。

每当您从文本框中读取值时,请使用Trim()作为textBox.Text.Trim()。 抱歉,它适用于SqlConnection。

由于