SQL Query只运行一次

时间:2015-07-27 09:44:01

标签: c# sql sql-server datagridview

我有以下代码:

SqlConnection con = new SqlConnection(@"Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True");
String Query;

for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
{
            MessageBox.Show(" " + this.dataGridView1.Columns.Count);
            MessageBox.Show(" " + this.dataGridView1.Columns[i].Name + " ");
            MessageBox.Show(" " + this.dataGridView1.SelectedRows[0].Cells[i].Value + " ");

            Query = "insert into [" + this.comboBox1.Text + "] ([" + this.dataGridView1.Columns[i].Name + "]) Values ('" + this.dataGridView1.SelectedRows[0].Cells[i].Value + "') ;";

            SqlCommand cmd = new SqlCommand(Query, con);

            con.Open();

            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter(Query, con);

            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;

            sda.SelectCommand = cmd;

            sda.Fill(dt);

            BindingSource bSource = new BindingSource();
            bSource.DataSource = dt;

            dataGridView1.DataSource = bSource;
        }
        con.Close();

它应该在表的每个列中插入一个特定的值(显示在dataGridView中),但在保存第一个值(我们要插入的行的第一列中的值)之后,它会刷新表并且只插入第一个值...我想插入整行

2 个答案:

答案 0 :(得分:1)

代码按预期正常运行。

这是你的代码:

for each column
 build sql string to take first row, current column and insert in db
 create sql command using the above sql string
 execute the above command
 refresh datagrid
next

上面会产生您正在经历的确切行为,这是预期的和正确的,因为代码完全按照告诉的方式执行。

根据您的描述,您的代码应该是什么:

for each row
 build base sql statement
 for each column
  add current value and field name to the base statement
 next
 create sql command
 fill the command with the statement built in the previous cycle
 execute the sql statement
next
refresh datagrid

如果您只需插入一行,则不需要外部foreach 执行字符串连接以构建语句时,需要处理输入清理和数据类型。

答案 1 :(得分:0)

con.open()应该在循环之外