【发布时间】:2016-07-03 20:15:36
【问题描述】:
我有一个带有 datagridview 工具的表单,所以我从第一个表单 datagridview 中的其他表单 datagridview 获取数据,并将数据从第一个表单 datagridview 插入到 sqlserver 数据库中。 第一种形式的 datagridview 列名是 从其他表单 datagridview 获取的 ItemName、数量、金额等,现在我想从第一个 datagridview 行中针对 ItemName 列插入 Itemcode,但我无法执行此操作。
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (ActiveControl == dataGridView1 && dataGridView1.CurrentCell == dataGridView1.CurrentRow.Cells[0]) // datagridview first cell enter event
{
ItemList fc = new ItemList() { OwnerForm = this };
fc.ShowDialog(this);
dataGridView1.CurrentRow.Cells[0].Value = ItemName;
dataGridView1.CurrentRow.Cells[4].Value = Item_MRP;
dataGridView1.CurrentRow.Cells[5].Value = Item_Purchase;
}
}
private void button1_Click(object sender, EventArgs e)
{
try {
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=mateenwin;User ID=sa;Password=123");
conn.Open();
SqlCommand commandd = new SqlCommand("SELECT MAX(Pur_Invoice_No)+1 FROM purchase", conn);
int InvoiceNo = Convert.ToInt32(commandd.ExecuteScalar());
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.IsNewRow) continue;
SqlConnection con = new SqlConnection("Data Source=.; Initial Catalog=mateenwin; User id=sa; password=123");
SqlCommand command = new SqlCommand("Insert into purchase (Pur_Invoice_No,Pur_Payment_Type_ID, Supplier_Bill_No,Supplier_ID,Item_Code,Pur_Item_Batch_No,Item_Batch_Expiry,Pur_Item_PackQuantity,Purchase_Pack_Price,Discount_Percentage,Extra_Discount_Percentage,MRP_Final,Login_ID,Pur_Entry_Date) values ('" + InvoiceNo + "','" + this.comboBox1.SelectedValue + "','" + this.textBox2.Text + "','" + this.comboBox2.SelectedValue + "','" + row.Cells[0].Value + "','" + row.Cells[1].Value + "','" + row.Cells[2].Value + "','" + row.Cells[3].Value + "','" + row.Cells[5].Value + "','" + row.Cells[6].Value + "','" + row.Cells[7].Value + "','" + row.Cells[4].Value + "','" + this.comboBox3.Text + "', GetDate())", con);
con.Open();
using (con)
{
command.ExecuteNonQuery();
}
}
MessageBox.Show("Invoice successfully Saved");
dataGridView1.Focus();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
【问题讨论】:
-
在您做任何其他事情之前,您需要阅读、理解和利用参数化查询以及它们如何防止 sql 注入。您的代码是 sql 注入漏洞的教科书示例。然后你需要阅读 sql server 中的 identity 属性。当你像你一样计算自己的时候,你有潜在的并发问题。最后但同样重要的是,你应该把你的连接字符串放在一个配置文件中,而不是到处硬编码。
-
这真的是 SQL 注入的教科书示例吗,因为它不是 Web 应用程序?
-
@Mr.B sql 注入不限于 Web 应用程序。该代码同样易受攻击。它可能不太可能受到影响,但这并不意味着代码不那么容易受到攻击。仅仅因为它不是一个网站并不意味着你应该参数化查询的想法是危险的。当它转换为网站时会发生什么?您必须更改所有查询?在我看来,不参数化查询是不负责任和懒惰的。做对很容易,做错就是疏忽。
-
那么,当你运行它时会发生什么?如果出现错误,则显示错误消息。如果没有,什么会发生或不会发生?定义“无法做到这一点”。请注意上面的建议 - 进行参数查询,无论是因为注入还是为了可读性,自动引用字符串等
标签: c# sql-server winforms datagridview