1

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

do it like this:

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

4 Comments

Thank you so much!
Never a good idea to use string concatenation for sql, even in demo/answer code.
Please do not advocate string concatenation. Show how to use parameterized queries or don't show it at all.
I knew it.. but he is just using a simple coding... it's just answering hes problem. No any sample code added except that query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.