I have a list off data like list=[{id:1,name:"ABC",age:12},{id:2,name:"QWE",age:21}]
I want to insert these data into database dynamically.
I googled and found how to insert a particular data. but dont know how to read the list andthen nsert those data.
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=source;Initial Catalog=testDB;User ID=ABCD;Password=password";
sql = "INSERT INTO TableName (id,name,age) VALUES('1','ABC',12)";
connection = new SqlConnection(connetionString);
try
{
connection.Open();;
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
cnx.Open(); // open cnx
if(List.Count !=0){ // if List isn't empty
for(int i = 0 i < List.Count ;i++)
{
// here he will execute one by one
string myQuery ="insert into TABLE_NAME values ('"+List[i][0]+"','"+List[i][1]+"','"+List[i][3]+"' ");
SqlCommand cmd = new SqlCommand(myQuery,cnx);
cmd.ExecuteNonQuery();
}
}
// i hope it's help you :))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.