如何在不使用存储过程的情况下,在C#中使用MySQLCommand创建一个安全的查询,以便在MySQL中执行大容量插入?
在下面的示例中,我构建了一个查询,以便对MySQL数据库进行批量插入:如何在不使用存储过程的情况下,在C#中使用MySQLCommand创建一个安全的查询,以便在MySQL中执行大容量插入?,c#,mysql,C#,Mysql,在下面的示例中,我构建了一个查询,以便对MySQL数据库进行批量插入: const string QUERY = "INSERT INTO contacts (first_name,last_name) VALUES{0};"; public string BuildQuery(IEnumerable<contact> contacts) { List<string> values = new List<string>(); foreach
const string QUERY = "INSERT INTO contacts (first_name,last_name) VALUES{0};";
public string BuildQuery(IEnumerable<contact> contacts)
{
List<string> values = new List<string>();
foreach (var contact in contacts)
{
values.Add(string.Format("('{0}','{1}')", contact.first_name, contact.last_name));
}
return string.Format(QUERY, string.Join(",", values));
}
如何编写一个不容易SQL注入的更安全的查询?您可以用与普通SQL命令几乎相同的方法来转义MySQL命令参数。下面是一个例子 请注意,无论您选择什么-从不通过用户字符串操作向SQL命令添加/插入参数。这是SQL注入攻击的主要来源
const string QUERY=“插入联系人(名字、姓氏)值”+
const string QUERY = "INSERT INTO contacts (first_name,last_name) VALUES" +
BuildQuery(c, contacts);
public string BuildQuery(MySQLCommand c, IEnumerable<contact> contacts)
{
List<string> values = new List<string>();
string query = null;
int i = 0;
foreach (var contact in contacts)
{
i++;
query += "(@firstName" + i + ", @lastName" + i + ")";
c.Parameters.AddWithValue("@firstName" + i, contact.first_name);
c.Parameters.AddWithValue("@lastName" + i, contact.last_name);
if(i < contacts.Count)
query += ",";
}
return query
}
BuildQuery(c,联系人);
公共字符串构建查询(mysqlc命令,IEnumerable联系人)
{
列表值=新列表();
字符串查询=null;
int i=0;
foreach(触点中的var触点)
{
i++;
查询+=“(@firstName“+i+”、@lastName“+i+”)”;
c、 Parameters.AddWithValue(“@firstName”+i,contact.first\u name);
c、 Parameters.AddWithValue(“@lastName”+i,contact.last_name);
如果(i
你可以看到一个!。我一定错过了一些琐碎的事情,但这对你来说是很琐碎的。当然,您知道当联系人没有任何元素时会发生什么。我看不到更多的边缘案例。顺便说一句,请注意,根据mysql允许的最大数据包大小,可以添加多少这样的参数是有限制的。您可以更改它,或者注意不要超过该限制。干杯!:) 在mysql中使用存储过程并在该函数中传递值。感谢您的建议,Romil!不幸的是,使用存储过程对我来说不是一个选项。希望有不同的解决方案。@您可以构造MysqlCommand参数,而不是查询本身。请参阅此链接以获取他所说的abt批量插入的答案!
private void PrepareExample()
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO mytable VALUES (?val)", myConnection);
cmd.Parameters.Add( "?val", 10 );
cmd.Prepare();
cmd.ExecuteNonQuery();
cmd.Parameters[0].Value = 20;
cmd.ExecuteNonQuery();
}
const string QUERY = "INSERT INTO contacts (first_name,last_name) VALUES" +
BuildQuery(c, contacts);
public string BuildQuery(MySQLCommand c, IEnumerable<contact> contacts)
{
List<string> values = new List<string>();
string query = null;
int i = 0;
foreach (var contact in contacts)
{
i++;
query += "(@firstName" + i + ", @lastName" + i + ")";
c.Parameters.AddWithValue("@firstName" + i, contact.first_name);
c.Parameters.AddWithValue("@lastName" + i, contact.last_name);
if(i < contacts.Count)
query += ",";
}
return query
}