如何使用c#将DataGridView数据插入到访问数据库的表中?

时间:2015-08-27 10:04:03

标签: c# datagridview ms-access-2010

我的程序首先将数据从excel导入datagridview,然后创建按钮在访问数据库中创建datagridview表,然后插入按钮将datagridview的所有数据插入到该表中。

我的查询对于某些excel数据工作正常但不适用于有1000行数据的大数据,我想更改我的查询,将所有类型的数据插入到数据库中,这是我的查询:

private void Create_Click(object sender, EventArgs e)
    {
        List<string> queries = new List<string>();
       queries.Add("CREATE TABLE " + textBox2.Text + " ( [" + DataGridView1.Columns[0].Name + "] Text, [" + DataGridView1.Columns[1].Name + "] Text, [" + DataGridView1.Columns[2].Name + "] Text, [" + DataGridView1.Columns[3].Name + "] Text, [" + DataGridView1.Columns[4].Name + "] Text, [" + DataGridView1.Columns[5].Name + "] Text, [" + DataGridView1.Columns[6].Name + "] Text)"); 


 private void btn_insert_Click(object sender, EventArgs e)
    {List<string> queries = new List<string>();
        foreach (DataGridViewRow row in DataGridView1.Rows)
        { if (!row.IsNewRow)
            {queries.Add("INSERT Into " + textBox2.Text + " (" + DataGridView1.Columns[0].Name + "," + DataGridView1.Columns[1].Name + "," + DataGridView1.Columns[2].Name + "," + DataGridView1.Columns[3].Name + "," + DataGridView1.Columns[4].Name + "," + DataGridView1.Columns[5].Name + "," + DataGridView1.Columns[6].Name + " ) values ('" + row.Cells[0].Value.ToString() + "','" + row.Cells[1].Value.ToString() + "','" + row.Cells[2].Value.ToString() + "','" + row.Cells[3].Value.ToString() + "','" + row.Cells[4].Value.ToString() + "','" + row.Cells[5].Value.ToString() + "','" + row.Cells[6].Value.ToString() + "')"); }
        }
        (ExecuteBatchUpdate(queries.ToArray()))

1 个答案:

答案 0 :(得分:-1)

List<string> queries = new List<string>();

foreach (DataGridViewRow row in DataGridView1.Rows)
{
    if (!row.IsNewRow)
    {
        queries.Add("Insert Into employee (empid,empname,sal) values ('" + row.Cells[0].Value.ToString() + "','" + row.Cells[1].Value.ToString() + "','" + row.Cells[2].Value.ToString() + "')");
    }
}