如何使用datagridview中的数据自动填充数据表?

时间:2017-06-29 14:19:06

标签: c# sql selenium automation

我正在尝试做的是自动化,在datagridview中接收数据,之后,我当前的问题,将其保存在sql中 我已经做了一些实验,到目前为止我得到了这个,

GDataPicker();
using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = conn;
            conn.Open();
            for (int x = 0; x < dataGridView1.Rows.Count; x++)
            {
                string strquery = @"INSERT INTO table_teste1 VALUES ("

                + dataGridView1.Rows[x].Cells["Rua"].Value + ", "
                + dataGridView1.Rows[x].Cells["Código Postal"].Value + ", "
                + dataGridView1.Rows[x].Cells["Distrito"].Value + ", "
                + dataGridView1.Rows[x].Cells["Concelho"].Value + ", "
                + dataGridView1.Rows[x].Cells["Freguesia"].Value + ", "
                + dataGridView1.Rows[x].Cells["GPS"].Value + ");";

                cmd.CommandText = strquery;
                cmd.ExecuteNonQuery();


            }
        }
        conn.Close();

此代码的问题在于我一直收到此信息 - &gt; System.Data.SqlClient.SqlException: 'Incorrect syntax near 'de'.'

有人试图帮助我,谢谢。

1 个答案:

答案 0 :(得分:2)

尝试此操作并进行更改

GDataPicker();
conn.Open();

for (int x = 0; x < dataGridView1.Rows.Count; x++)
{
    cmd.Parameters.Add(new SqlParameter("@Rua", SqlDbType.VarChar, 255, "Rua"));
    cmd.Parameters.Add(new SqlParameter("@Codigo Postal", SqlDbType.VarChar, 255, "Codigo Postal"));
    cmd.Parameters.Add(new SqlParameter("@Distrito", SqlDbType.VarChar, 255, "Distrito"));
    cmd.Parameters.Add(new SqlParameter("@Concelho", SqlDbType.VarChar, 255, "Concelho"));
    cmd.Parameters.Add(new SqlParameter("@Freguesia", SqlDbType.VarChar, 255, "Freguesia"));
    cmd.Parameters.Add(new SqlParameter("@GPS", SqlDbType.VarChar, 255, "GPS"));

    cmd.Parameters["@Rua"].Value = dataGridView1.Rows[x].Cells[0].Value.ToString();
    cmd.Parameters["@Codigo Postal"].Value = dataGridView1.Rows[x].Cells[1].Value.ToString();
    cmd.Parameters["@Distrito"].Value = dataGridView1.Rows[x].Cells[2].Value.ToString();
    cmd.Parameters["@Concelho"].Value = dataGridView1.Rows[x].Cells[3].Value.ToString();
    cmd.Parameters["@Freguesia"].Value = dataGridView1.Rows[x].Cells[4].Value.ToString();
    cmd.Parameters["@GPS"].Value = dataGridView1.Rows[x].Cells[5].Value.ToString();

    cmd = new SqlCommand(strquery);
    cmd.Connection = con;

    cmd.ExecuteNonQuery();
}
conn.Close();