[c#] How to insert Records in Database using C# language?

I am just a begginer on C# so i need too much help. Now the problem is that i have designed a windows form in which there are many fields like first name, last name, address etc. Now i want to do is that when i fill the form and click insert button all the information goes into database. Does anyone know how to do that?

private void button1_Click(object sender, System.EventArgs e)
{
    string connetionString = null;
    SqlConnection cnn ;
    SqlDataAdapter adapter = new SqlDataAdapter();
    string sql = null;
    connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;

    cnn = new SqlConnection(connetionString);
    sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";

    try
    {
        cnn.Open();
        adapter.InsertCommand = new SqlCommand(sql, cnn);
        adapter.InsertCommand.ExecuteNonQuery();
         MessageBox.Show ("Row inserted !! ");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

This question is related to c# database visual-studio-2008

The answer is


Use a parameterized query to prevent Sql injections (secutity problem)

Use the using statement so the connection will be closed and resources will be disposed.

using(var connection = new SqlConnection("connectionString"))
{
    connection.Open();
    var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
    using(var cmd = new SqlCommand(sql, connection))
    {
        cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
        cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);

        cmd.ExecuteNonQuery();
    }
}

There are many problems in your query.
This is a modified version of your code

string connetionString = null;
string sql = null;

// All the info required to reach your db. See connectionstrings.com
connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;

// Prepare a proper parameterized query 
sql = "insert into Main ([Firt Name], [Last Name]) values(@first,@last)";

// Create the connection (and be sure to dispose it at the end)
using(SqlConnection cnn = new SqlConnection(connetionString))
{
    try
    {
       // Open the connection to the database. 
       // This is the first critical step in the process.
       // If we cannot reach the db then we have connectivity problems
       cnn.Open();

       // Prepare the command to be executed on the db
       using(SqlCommand cmd = new SqlCommand(sql, cnn))
       {
           // Create and set the parameters values 
           cmd.Parameters.Add("@first", SqlDbType.NVarChar).Value = textbox2.text;
           cmd.Parameters.Add("@last", SqlDbType.NVarChar).Value = textbox3.text;

           // Let's ask the db to execute the query
           int rowsAdded = cmd.ExecuteNonQuery();
           if(rowsAdded > 0) 
              MessageBox.Show ("Row inserted!!" + );
           else
              // Well this should never really happen
              MessageBox.Show ("No row inserted");

       }
    }
    catch(Exception ex)
    {
        // We should log the error somewhere, 
        // for this example let's just show a message
        MessageBox.Show("ERROR:" + ex.Message);
    }
}
  • The column names contain spaces (this should be avoided) thus you need square brackets around them
  • You need to use the using statement to be sure that the connection will be closed and resources released
  • You put the controls directly in the string, but this don't work
  • You need to use a parametrized query to avoid quoting problems and sqlinjiection attacks
  • No need to use a DataAdapter for a simple insert query
  • Do not use AddWithValue because it could be a source of bugs (See link below)

Apart from this, there are other potential problems. What if the user doesn't input anything in the textbox controls? Do you have done any checking on this before trying to insert? As I have said the fields names contain spaces and this will cause inconveniences in your code. Try to change those field names.

This code assumes that your database columns are of type NVARCHAR, if not, then use the appropriate SqlDbType enum value.

Please plan to switch to a more recent version of NET Framework as soon as possible. The 1.1 is really obsolete now.

And, about AddWithValue problems, this article explain why we should avoid it. Can we stop using AddWithValue() already?


You should form the command with the contents of the textboxes:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + 
"," + textbox3.Text+ ")";

This, of course, provided that you manage to open the connection correctly.

It would be helpful to know what is happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.

You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code).


You should change your code to make use of SqlParameters and adapt your insert statement to the following

string connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// [ ] required as your fields contain spaces!!
string insStmt = "insert into Main ([First Name], [Last Name]) values (@firstName,@lastName)";

using (SqlConnection cnn = new SqlConnection(connetionString))
{
    cnn.Open();
    SqlCommand insCmd = new SqlCommand(insStmt, cnn);
    // use sqlParameters to prevent sql injection!
    insCmd.Parameters.AddWithValue("@firstName", textbox2.Text);
    insCmd.Parameters.AddWithValue("@lastName", textbox3.Text);
    int affectedRows = insCmd.ExecuteNonQuery();
    MessageBox.Show (affectedRows + " rows inserted!");
}

You should form the command with the contents of the textboxes:

sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";

This, of course, provided that you manage to open the connection correctly.

It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.

You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).


sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";

(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to database

Implement specialization in ER diagram phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' cannot be loaded Room - Schema export directory is not provided to the annotation processor so we cannot export the schema SQL Query Where Date = Today Minus 7 Days MySQL Error: : 'Access denied for user 'root'@'localhost' SQL Server date format yyyymmdd How to create a foreign key in phpmyadmin WooCommerce: Finding the products in database TypeError: tuple indices must be integers, not str

Examples related to visual-studio-2008

Convert Text to Uppercase while typing in Text box SQL Server r2 installation error .. update Visual Studio 2008 to SP1 What is and how to fix System.TypeInitializationException error? Error LNK2019: Unresolved External Symbol in Visual Studio download and install visual studio 2008 Git in Visual Studio - add existing project? Visual Studio can't 'see' my included header files How to insert Records in Database using C# language? If statements for Checkboxes LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup