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:

  • Can an INNER JOIN offer better performance than EXISTS
  • SQL Server 2012 Remote Connection setup
  • Simple t-sql instead of trigger
  • copy FOREIGN KEY constraints from one DB to other
  • Insert Data into MSSQL DB using PHP
  • Update statement error: Subquery returned more than 1 value
  • 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?

  • How can we check that table have index or not?
  • How to get Previous Value for Null Values
  • Is it possible to have temp tables in a function?
  • Extracting data from MS SQL Server-2008 referring multiple tables
  • Select Max from each Subset
  • ODBC continually prompts for password
  • 3 Solutions collect form web for “Using Database from SQL Server in Visual Studio”

    do it like this:

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

    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.

    Generally, it would be bad practice to generate SQL inline like this, but ignoring that, I think you’re just missing a few single quotes, a space, and a comma.

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

    You might also find it easier to use String.Format like this:

    string sql = String.Format("INSERT INTO user1(username, password) VALUES('{0}', '{1}')", textBox1.Text, textBox2.Text);
    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.