简体   繁体   中英

Using Database from SQL Server in Visual Studio

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?

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.

像这样做:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM