sql语法错误 - 无法将字符串追加到数据库

时间:2018-02-19 12:50:46

标签: c# sql database syntax-error

我目前正在制作一个虚拟项目,我正在制作登录屏幕。除了学习一些C#和sql之外,我对这个项目没有太大的意图。

我目前正在尝试将新用户添加到包含每个用户名及其密码的数据库,但我出于某种原因收到错误消息。

文本框中写的条目应存储在数据库中,但出于某种原因,这种情况不会发生..

我收到一条错误,指出我有语法错误,我不确定我理解。

private void create_user_username_box_Leave(object sender, EventArgs e)
{
     // Add user/password to database when when someone leaves the area. 
     using (DbConnection connection = new SqlConnection(@"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
     {
         connection.Open();
         using (DbCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
         {
             command.Connection = connection;
             command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
         }                


    }                
}

3 个答案:

答案 0 :(得分:2)

永远不要执行以下操作

"INSERT INTO [dbo].[information] (id,password) 
     VALUES (" + someStringVariable + "," + someOtherStringVariable + ")"

想想你在这里做了什么 - 你将用户输入的任何文字直接放入你的查询字符串中。这是丢弃数据库或其中包含的所有信息被盗的最简单方法。

相反,请使用预准备语句

     var commandText = "INSERT INTO [dbo].[information] (id,password) VALUES (@Username, @Password)"

     using (var command = new SqlCommand(commandText, connection))
     {
         command.Parameters.Add("@Username", SqlDbType.VarChar).Value = create_user_username_textbox.Text
         command.Parameters.Add("@Password", SqlDbType.VarChar).Value = create_user_password_textbox.Text
         command.ExecuteNonQuery(); 
     } 

您还应该强烈考虑不以纯文本格式存储密码

更新了替换Parameters.AddWithValue的建议 - 显然,如果数据库中的列类型不同,请相应地设置

答案 1 :(得分:0)

值是字符串,因此生成的SQL命令文本应将它们用单引号括起来。

public class FileMessageComparator implements Comparator<Message<File>> {..}

但是,您应该真正参数化查询以防止可能发生Sql注入攻击。

将字符串更改为:

VALUES ('"+create_user_username_textbox.Text+"','"...

为命令添加参数:

VALUES (@id,@pw)"))

答案 2 :(得分:-4)

试试这个 -

private void create_user_username_box_Leave(object sender, EventArgs e)
{
 // Add user/password to database when when someone leaves the area. 
 using (SqlConnection connection = new SqlConnection(@"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
 {
     connection.Open();
     using (SqlCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id,password) VALUES ("+create_user_username_textbox.Text+","+create_user_password_textbox.Text+");"))
     {
         command.Connection = connection;
         command.ExecuteNonQuery(); // System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
     }                


}                
}