how do you add data to sql database using c# variables and an sql command? I have a class of employes that i use which has values identical to my sql database tables
here is the basic code of what i want to do...

SDC.DbCommand dbCmd; //database command

string sql = string.Format(INSERT INTO employeeTable(EmployeeName, Salary) VALUES ('James Peter', 42000);  
//works but i need to convert and use the employee class values like i did below

employee newEmployee = new Employee("James Peter", 4200);
string sql = string.Format(INSERT INTO employeeTable(EmployeeName, Salary) VALUES ('newEmployee.EmployeeName', newEmployee.Salary); 

dbCmd.CommandText = sql;

How should i go about doing this? should i use a substring or is there a SQl command
i could use to make things much easier.

i keep getting an error saying my index is invalid but shouldnt my id number be automatically assigned?

8 Years
Discussion Span
Last Post by dickersonka

Try something like:

string query ="INSERT INTO emptable(Name,Sal) VALUES(aname,asalary)";
SqlCommand cmd = new SqlCommand(query, connection);

I don't see why you should format your string.


i think maybe a small correction to that, since he is getting them from the newEmployee object

string sql = "INSERT INTO employeeTable(EmployeeName, Salary) VALUES ('" + newEmployee.EmployeeName + "', " + newEmployee.Salary.ToString() + ")";
Votes + Comments
Errare humanum est! Aways correct me if you think you must.
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.