【发布时间】:2014-01-22 02:06:49
【问题描述】:
尝试将数据插入数据库时出现此错误。
System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的未处理异常
附加信息:关键字“用户”附近的语法不正确。
代码如下:
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(
Properties.Settings.Default.BlackBookDBConnectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO User (Username, Password, SecurityQuestionOne, "
+ "SecurityQuestionTwo, SecurityAnswerOne, SecurityAnswerTwo); VALUES ("
+ txtRegisterUsername.Text + ","
+ txtRegisterPassword.Text + ","
+ lstRegisterSecurityQuestionOne.SelectedText + ","
+ lstRegisterSecurityQuestionTwo.SelectedItem + ","
+ txtRegisterSecurityAnswerOne.Text + ","
+ txtRegisterSecurityAnswerTwo.Text + ")";
cmd.CommandText = "INSERT INTO USer ()";
cmd.Connection = connection1;
connection1.Open();
cmd.ExecuteNonQuery();
connection1.Close();
}
我已经编辑了我的代码。但是由于某种原因,它仍然没有向我的数据库中插入任何内容。
if(txtRegisterSecurityAnswerOne.TextLength >0 && txtRegisterSecurityAnswerTwo.TextLength >0)
{
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);
string sqlquery = "INSERT INTO [User] (Username,Password,SecurityQuestionOne,"
+ "SecurityAnswerOne,SecurityQuestionTwo,SecurityAnswerTwo) "
+ "VALUES (@Username,@Password,@QuestionOne,@AnswerOne,@QuestionTwo,@AnswerTwo)";
SqlCommand command = new SqlCommand(sqlquery, connection1);
string userName = txtRegisterUsername.Text;
command.Parameters.AddWithValue("Username", userName);
string password = txtRegisterRepeatPassword.Text;
command.Parameters.AddWithValue("Password", password);
string questionOne = lstRegisterSecurityQuestionOne.SelectedText;
command.Parameters.AddWithValue("QuestionOne", questionOne);
string questionTwo = lstRegisterSecurityQuestionTwo.SelectedText;
command.Parameters.AddWithValue("QuestionTwo", questionTwo);
string answerOne = txtRegisterSecurityAnswerOne.SelectedText;
command.Parameters.AddWithValue("AnswerOne", answerOne);
string answerTwo = txtRegisterSecurityAnswerTwo.SelectedText;
command.Parameters.AddWithValue("AnswerTwo", answerTwo);
command.Connection = connection1;
connection1.Open();
command.ExecuteNonQuery();
connection1.Close();
}
【问题讨论】:
-
使用占位符。 缺乏使用是(或者更确切地说,一个)直接问题(因为没有正确引用值),使用他们将避免将来出现问题 - 意外或恶意 SQL 注入。
-
您正在乞求 SQL 注入攻击。请考虑使用参数进行内联查询。 stackoverflow.com/questions/4624811/…
-
你的连接字符串是什么?
-
SqlConnection connection1 = new SqlConnection(Properties.Settings.Default.BlackBookDBConnectionString);连接1.Open();
-
你的连接字符串是什么样子的?(它的内容)
标签: c# sql-server database