我创建了以下插入方法,该方法运行得相当好,但我知道它可能更有效。有人可以告诉我如何将此方法转换为使用参数和/或提高效率吗?
public static void SQLiteTableINSERT(string tableName)
{
int colCount = 0;
using (SQLiteConnection Conn = new SQLiteConnection(SQLiteConn.Conn))
{
using (SQLiteTransaction sqliteTrans = Conn.BeginTransaction())
{
using (SQLiteCommand cmd = Conn.CreateCommand())
{
DataTableColumnNames();
string query = "INSERT INTO " + tableName + "(";
foreach (string name in DtColumns)
{
query += "[" + name + "]";
++colCount;
if (colCount < DtColumns.Count())
query += ",";
}
query += ")";
query += " VALUES(";
for (int i = 0; i < LocalDataSet.LocalDs.Tables[0].Rows.Count; ++i)
{
cmd.CommandText = query;
foreach (DataColumn col in LocalDataSet.LocalDs.Tables[0].Columns)
{
string temp = LocalDataSet.LocalDs.Tables[0].Rows[i][col, DataRowVersion.Current].ToString();
if (temp == "True")
cmd.CommandText += 1;
else if (temp == "")
cmd.CommandText += 0;
if (temp != "True" && temp != "")
cmd.CommandText += "'" +temp + "'";
cmd.CommandText += ",";
}
cmd.CommandText = cmd.CommandText.Remove(cmd.CommandText.LastIndexOf(","));
cmd.CommandText += ")";
cmd.ExecuteNonQuery();
}
}
sqliteTrans.Commit();
}
}
}
答案 0 :(得分:1)
您真的应该将其切换为使用预准备语句,然后将数据绑定到该预准备语句中的参数。这里解释了C / C ++的基础知识:
http://www.sqlite.org/cintro.html
我怀疑你使用的是dotConnect,所以你可能想要参考这个特定的例子:
http://www.devart.com/dotconnect/sqlite/docs/Parameters.html
同样的原则适用。您将SQL编写为单个字符串常量,在源代码中易于阅读,查看和修改。然后将该SQL命令与一组数据元素一起发送到SQLite以替换每个参数。这种技术使您的代码更加清晰,有助于避免SQL注入攻击或混乱。