sql server - How to insert multiple records into database with SqlParameter in C# -
i trying run following code:
using (sqlconnection conn = new sqlconnection(connstr)) { conn.open(); stringbuilder sqlstr = new stringbuilder("insert customers values ( @name, @address, @city, @state)"); sqlcommand cmd = new sqlcommand(sqlstr.tostring(), conn); cmd.parameters.add(new sqlparameter("@name", "john smith")); cmd.parameters.add(new sqlparameter("@address", "123 main st.")); cmd.parameters.add(new sqlparameter("@city", "detroit")); cmd.parameters.add(new sqlparameter("@state", "michigan")); cmd.executereader(); cmd.parameters["@name"].value = "william jones"; cmd.parameters["@address"].value = "500 blanchard ave"; cmd.parameters["@city"].value = "chicago"; cmd.parameters["@state"].value = "illinois"; cmd.executereader(); }
however, getting error. have tried multiple other ways, nothing seems work. proper way insert multiple records using sqlparameter
s?
first of cmd.executereader();
used on data retrieval , not not proper way in doing insert.
use
cmd.executenonquery();
change code this:
create method has 4 parameter pass name,address,city , state includes insert code
private void insertcustomers(string name,string address,string city,string state) { using (sqlconnection conn = new sqlconnection(connstr)) { conn.open(); stringbuilder sqlstr = new stringbuilder("insert customers values ( @name, @address, @city, @state)"); sqlcommand cmd = new sqlcommand(sqlstr.tostring(), conn); cmd.parameters.add(new sqlparameter("@name", name)); cmd.parameters.add(new sqlparameter("@address", address)); cmd.parameters.add(new sqlparameter("@city", city)); cmd.parameters.add(new sqlparameter("@state", state)); cmd.executenonquery(); } }
then on click or events want insert new customer do
insertcustomers("a","b","c","d"); insertcustomers("e","f","g","h");
and maybe need start learning basic first on ado.net
the c# station ado.net tutorial
after completing tutorial, familiarize on ado.net.
best regards
Comments
Post a Comment