从datagridview c#向数据库添加数据 [英] adding data to database from datagridview c#
本文介绍了从datagridview c#向数据库添加数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
while i was searching in google i find a code to add the items from datagridview to database using c#
<pre lang="c#">for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
string strCmd = @"Insert into Bills(itemname) values(" + dataGridView1.Rows[i].Cells[0].Value + ")";
SqlCommand Cmd = new SqlCommand(strCmd, Con);
Cmd.ExecuteNonQuery();
}
就像dataGridView1.Rows [i] .Cells [ 1] .Value +);当我把它改为.Cells [0]
i得到了这个错误
语法附近3
the was like that dataGridView1.Rows[i].Cells[1].Value + ")"; when i chang it to .Cells[0]
i got that error
incorrect syntax near 3
推荐答案
使用正确参数化的查询将修复 SQL注入 [ ^ ]漏洞,并修复了您看到的错误:
Using a properly parameterized query will fix the SQL Injection[^] vulnerability in your code, and also fix the error you're seeing:
using (SqlConnection connection = new SqlConnection("-YOUR CONNECTION STRING-"))
using (SqlCommand command = new SqlCommand("INSERT INTO Bills (ItemName) VALUES (@ItemName)", connection))
{
SqlParameter pItemName = command.Parameters.Add("@ItemName", SqlDbType.VarChar, 50);
connection.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
pItemName.Value = dataGridView1.Rows[i].Cells[0].Value ?? DBNull.Value;
command.ExecuteNonQuery();
}
}
你想知道关于SQL注入的一切(但不敢问)特洛伊亨特 [ ^ ]
如何在没有技术术语的情况下解释SQL注入? |信息安全堆栈交换 [ ^ ]
SQL注入攻击机制Pluralsight [ ^ ]
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
SQL injection attack mechanics | Pluralsight [^]
这篇关于从datagridview c#向数据库添加数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文