C# 在C中将datagridview中的值插入SQL Server数据库
我在SQLServer数据库中有两个表,product和innvoice 我正在从表product中获取所选数据,并在datagridview中显示它们 现在我想将数据从datagridview存储到表InVoice。所有操作只需单击一个按钮 这是我的密码:C# 在C中将datagridview中的值插入SQL Server数据库,c#,sql-server,database,datagrid,C#,Sql Server,Database,Datagrid,我在SQLServer数据库中有两个表,product和innvoice 我正在从表product中获取所选数据,并在datagridview中显示它们 现在我想将数据从datagridview存储到表InVoice。所有操作只需单击一个按钮 这是我的密码: private void button5_Click_2(object sender, EventArgs e) //add produt { SqlConnection con = new SqlConnection(@"
private void button5_Click_2(object sender, EventArgs e) //add produt
{
SqlConnection con = new SqlConnection(@"Persist Security Info=False;User ID=usait;password=123;Initial Catalog=givenget;Data Source=RXN-PC\ROSHAAN");
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT product.p_name,product.p_category, product.sale_price FROM product where p_code='" + textBox16.Text + "'", con);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView3.DataSource = dt;
// here I want to insert values from datagridview3 to table innvoice.
}
请注意,使用直接SQL查询不是一个好的做法 希望这对你有帮助
private void button5_Click_2(object sender, EventArgs e) //add produt
{
SqlConnection con = new SqlConnection(@"Persist Security Info=False;User ID=usait;password=123;Initial Catalog=givenget;Data Source=RXN-PC\ROSHAAN");
Dataset ds=new Dataset();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT product.p_name,product.p_category, product.sale_price FROM product where p_code='" + textBox16.Text + "'", con);
da.Fill(ds);
dataGridView3.DataSource = ds;
//Code to insert values into Invoice
for( i = 0; i < ds.Tables[0].Rows.Count; i++)
{
sqlcommand cmd=new sqlcommand();
cmd=new sqlcommand("insert into invoice(pname,pcategory,psaleprice) values('"+ds.Tables[0].Rows[i]["product.p_name"].ToString()+"','"+ds.Tables[0].Rows[i]["product.p_category"].ToString()+"','"+ds.Tables[0].Rows[i]["product.sale_price"].ToString()+"')",con);
cmd.executeNonquery();
}
con.close();
}
您需要一个插入查询。看在上帝的份上,搜索一下……这是发票——只有一张n。你们应该停止把你们的SQL语句连接在一起——这只是在邀请黑客利用你们的SQL注入弱点!始终使用参数化查询。您可以从dt插入记录,而不是dataGridView。我不确定两个表的架构结构是什么样的,但您最好使用products表中的Id作为发票表中的外键。这样,发票表只包含发票特定的信息,而不是到处复制信息。