2017-06-06 41 views
1

我在Visual Studio中做了一個C#項目。爲了項目的目的,我需要包含來自SQL Server的數據庫。在Visual Studio中使用SQL Server中的數據庫

以下是我已經寫在SQL Server中:(!從數據庫中讀取做工不錯)

create table user1 (
    id int primary key identity, 
    username varchar(50), 
    password varchar(50)); 

然後,在Visual Studio中,我要特別強調將在數據庫中插入值的形式。這裏是我的代碼:

string sql = "INSERT INTO user1(username, password) VALUES ('"+textBox1.Text + "'+" + textBox2.Text+")"; 

但我得到一個錯誤信息:

System.Data.SqlClient.SqlException:有在INSERT語句中列大於VALUES子句中指定的值。 VALUES子句中的值數量必須與INSERT語句中指定的列數相匹配。

我在做什麼錯?

回答

-1

做這樣的:

string sql = "INSERT INTO user1(username, password) VALUES ('"+textBox1.Text + "','" + textBox2.Text+"')"; 
+0

非常感謝! – pang

+0

如果這解決了你的問題,然後標記爲已回答。 –

+2

從不是一個好主意,即使在演示/答案代碼中使用字符串連接的SQL。 –

4

避開直接從用戶構建SQL語句與輸入的。這隻會導致您用SQL注入攻擊來解決問題。改用參數化的SQL。如下所示。

string sql = "INSERT INTO user1(username, password) VALUES (@username, @password)"; 
command.CommandText = sql; 
command.Parameters.Add(new SqlParameter("@userName", textBox1.Text)); 
command.Parameters.Add(new SqlParameter("@password", textBox2.Text)); 

話雖如此,我還強烈勸阻你以純文本存儲用戶密碼。這會讓你進入後來在賽道上受傷的世界。

相關問題