如何在表中插入多个值?使用c# [英] how to insert multiple values in a table? using c#
本文介绍了如何在表中插入多个值?使用c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何编写用于在不同的表中插入新值的代码....在多行中
i hv使用以下代码在一个新行中插入新值我从组合框中选择的不同表格数据 -
how to write code for inserting new values in different tables....in multiple rows
i hv used the following code to insert new values in one new row of different tables dat i select from combo box-
connectionString = @"Data Source=HP\SQLEXPRESS;database=MK;Integrated Security=true";
connection = new SqlConnection(connectionString);
foreach (int rowIndex in lstNewRows)
{
string insrtQry = "insert into " + comboBox1.Text + " values(";
foreach (DataGridViewCell cell in dataGridView1.Rows[rowIndex].Cells)
{
insrtQry += "'" + cell.Value.ToString() + "',";
}
insrtQry = insrtQry.TrimEnd(",".ToCharArray());
insrtQry += ")";
try
{
connection.Open();
adapter.InsertCommand = new SqlCommand(insrtQry, connection);
adapter.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Row inserted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void insert_Click(object sender, EventArgs e)
{
InsertInfo();
}
private void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
lstNewRows.Add(e.Row.Index);
}
推荐答案
查找交易
:允许多个查询要作为块执行。如果其中一个查询失败,您可以执行回滚
以进入数据库的先前状态。
顺便提一下,建议使用参数化查询
:它们有助于防止SQL注入攻击,它们有助于处理奇数数据类型(例如日期时间值或带引号的字符串)。
Look forTransaction
: that allows for several queries to be executed as a block. If one of the queries fails, you can do aRollback
to get to the previous state of your database.
By the way, it is advisable to useparameterized queries
: they help prevent SQL injection attacks, and they help dealing with odd datatypes (e.g. datetime values or strings with quotation marks).
>
这篇关于如何在表中插入多个值?使用c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文