Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert data into SQL Server

Tags:

What the problem on my coding? I cannot insert data to ms sql.. I'm using C# as front end and MS SQL as databases...

name = tbName.Text; userId = tbStaffId.Text; idDepart = int.Parse(cbDepart.SelectedValue.ToString());  string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) " +                    " VALUES ('" + name + "', '" + userId +"', '" + idDepart + "');";  SqlCommand querySaveStaff = new SqlCommand(saveStaff);  try { querySaveStaff.ExecuteNonQuery(); } catch { //Error when save data  MessageBox.Show("Error to save on database"); openCon.Close(); Cursor = Cursors.Arrow; } 
like image 372
Azri Zakaria Avatar asked Sep 03 '12 01:09

Azri Zakaria


People also ask

How do you data insert in SQL Server?

INSERT INTO Syntax 1. Specify both the column names and the values to be inserted: INSERT INTO table_name (column1, column2, column3, ...)

How can insert data in database table in SQL?

Syntax: INSERT INTO table_name(column_name1, column_name2...) VALUES(column1_value, column2_value...); Here, we will insert data into the following Employee table which we created in the Create Table chapter.


1 Answers

You have to set Connection property of Command object and use parametersized query instead of hardcoded SQL to avoid SQL Injection.

 using(SqlConnection openCon=new SqlConnection("your_connection_String"))     {       string saveStaff = "INSERT into tbl_staff (staffName,userID,idDepartment) VALUES (@staffName,@userID,@idDepartment)";        using(SqlCommand querySaveStaff = new SqlCommand(saveStaff))        {          querySaveStaff.Connection=openCon;          querySaveStaff.Parameters.Add("@staffName",SqlDbType.VarChar,30).Value=name;          .....          openCon.Open();           querySaveStaff.ExecuteNonQuery();        }      } 
like image 62
KV Prajapati Avatar answered Oct 16 '22 18:10

KV Prajapati