120-c-sharp-sql-insert-command

Easier way to connect to database is

In this tutorial C Sharp SQL Insert command is explained, i.e. how SQL Insert Command is implemented in C#. We continue from previous example.

string str_sql_insert = ” insert into PERSON “;
str_sql_insert += ” ( NAME, SURNAME, EMAIL, PHONE ) “;
str_sql_insert += ” values “;
str_sql_insert += ” ( “;
str_sql_insert += ” @Name, “;
str_sql_insert += ” @Surname, “;
str_sql_insert += ” @Email, “;
str_sql_insert += ” @Phone “;
str_sql_insert += ” ) “;

sqlCmd.Parameters.AddWithValue(“Name”,txtName.Text );
sqlCmd.Parameters.AddWithValue(“Surname”, txtSurname.Text);
sqlCmd.Parameters.AddWithValue(“Email”, txtEmail.Text);
sqlCmd.Parameters.AddWithValue(“Phone”, txtPhone.Text);

sqlCn.Open();
sqlCmd.CommandText = str_sql_insert;
sqlCmd.ExecuteNonQuery();
sqlCn.Close();

sqlCmd.Parameters.Clear();
list_of_persons();

If, however, database is not set to auto increment ID, corresponding code would be:

int int_id = 0;
string str_sql_select_max = ” select max(PERSON.ID_PERSON) from PERSON “;

sqlCn.Open();
sqlCmd.CommandText = str_sql_select_max;
int_id = Convert.ToInt32(sqlCmd.ExecuteScalar());
sqlCmd.ExecuteNonQuery();
sqlCn.Close();

int_id++;

string str_sql_insert = ” insert into PERSON “;
str_sql_insert += ” (ID_PERSON , NAME, SURNAME, EMAIL, PHONE) “;
str_sql_insert += ” values “;
str_sql_insert += ” ( “;
str_sql_insert += ” @ID, “;
str_sql_insert += ” @Name, “;
str_sql_insert += ” @Surname, “;
str_sql_insert += ” @Email, “;
str_sql_insert += ” @Phone “;
str_sql_insert += ” ) “;

sqlCmd.Parameters.AddWithValue(“ID”, SqlDbType.BigInt).Value = int_id;
sqlCmd.Parameters.AddWithValue(“Name”, txtName.Text);
sqlCmd.Parameters.AddWithValue(“Surname”, txtSurname.Text);
sqlCmd.Parameters.AddWithValue(“Email”, txtEmail.Text);
sqlCmd.Parameters.AddWithValue(“Phone”, txtPhone.Text);

sqlCn.Open();
sqlCmd.CommandText = str_sql_insert;
sqlCmd.ExecuteNonQuery();
sqlCn.Close();

sqlCmd.Parameters.Clear();
list_of_persons();

If, however parametric mapping of the text is not working in your application, you can use following function for special characters.

External links:

C Sharp SQL Insert Command on Microsoft
C Sharp SQL Insert Command on Codeproject
C Sharp SQL Insert Command on Daniweb

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*