Reputation:
I am doing a C# project in Visual Studio. For the purposes of the project, I need to include a database from SQL Server.
Here is what I have written in SQL Server:
create table user1 (
id int primary key identity,
username varchar(50),
password varchar(50));
Then, in the Visual Studio, I want to make a form that will insert values in the database (reading from the database works good!). Here is my code:
string sql = "INSERT INTO user1(username, password) VALUES ('"+textBox1.Text + "'+" + textBox2.Text+")";
But I get an error message:
System.Data.SqlClient.SqlException: There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
What am I doing wrong?
Upvotes: 1
Views: 86
Reputation: 7941
Steer clear of constructing SQL statements with input directly from the user. this is only going to cause you trouble down the track with SQL Injection attacks. Use parameterised SQL instead. like the following.
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));
Having said that I would also strongly discourage you from storing user passwords in plain text. This will open you up to a world of hurt later on down the track.
Upvotes: 4
Reputation: 4211
do it like this:
string sql = "INSERT INTO user1(username, password) VALUES ('"+textBox1.Text + "','" + textBox2.Text+"')";
Upvotes: -1