我创建了一个ComboBox,其中显示了我数据库中表的所有名称。当我单击一个按钮时,当前的表显示在DataGridView中。我已经成功创建了一个Insert按钮来在当前表中添加新数据,但它没有更新我的数据库中的信息......这是代码:
private void insertBttn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True");
int i = 0;
// SqlDataAdapter sda;
con.Open();
for (i = 0; i < this.dataGridView1.Rows.Count; i++)
{
string query = "insert into " + comboBox1.SelectedValue.ToString() + " (@" + dataGridView1.Columns[i] + ") VALUES ('" + this.dataGridView1.Columns[i] + "');";
SqlCommand cmd = new SqlCommand(query, con);
}
con.Close();
答案 0 :(得分:0)
更改您的代码并检查
protected void insertBttn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
int i = 0;
int j = 0;
string query = "";
string columnText = "";
string valueText = "";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
for (i = 0; i < dataGridView1.Rows.Count; i++)
{
columnText = "";
valueText = "";
for (j = 0; j < dataGridView1.Rows[0].Cells.Count; j++)
{
if (j != 0)
{
columnText += ",";
valueText += ",";
}
columnText += dataGridView1.HeaderRow.Cells[j].Text;
valueText += "'" + dataGridView1.Rows[i].Cells[j].Text + "'";
}
query += "insert into " + comboBox1.SelectedValue.ToString() + " (" + columnText + ") values (" + valueText + ")";
}
try
{
cmd.CommandText = query;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
finally
{
con.Close();
}
}
答案 1 :(得分:0)
基本上你缺少两个关键结构:
您的代码已编辑:
private void insertBttn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=NUC\MICROGARDE;Initial Catalog=SQL;Integrated Security=True");
int i = 0;
con.Open();
for (i = 0; i < this.dataGridView1.Rows.Count; i++)
{
string query = "insert into " + comboBox1.SelectedValue.ToString() + " (@" + dataGridView1.Columns[i] + ") VALUES ('" + this.dataGridView1.Columns[i] + "');";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter(@Field, "value"));
cmd.Parameters.Add(new SqlParameter(@Field, "value"));
cmd.ExecuteNonQuery();
}
con.Close();
}
使用参数也可以阻止SQL注入。