簡體   English   中英

sql語法錯誤-無法將字符串追加到數據庫

[英]sql syntax error - not able to append string to a database

我目前正在做一個虛擬項目,正在制作一個登錄屏幕。 除了學習一些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 ')'.'
         }                


    }                
}

永遠不要執行以下操作

"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顯然,如果數據庫上的列類型不同,則進行相應設置

這些值是字符串,因此生成的SQL命令文本應將它們用單引號引起來。

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

但是,您應該真正對查詢進行參數設置,以防止潛在的Sql注入攻擊。

將字符串更改為:

VALUES (@id,@pw)"))

向命令添加參數:

command.Parameters.Add(new SqlParameter("@id", create_user_username_textbox.Text));
command.Paramaters.Add(new SqlParameter("@pw", create_user_password_textbox.Text));

嘗試這個 -

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 ')'.'
     }                


}                
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM