我开发了一种方法,允许我通过参数传入表(字符串)、列数组(字符串)和值数组(对象),然后我使用这些参数创建参数化查询。尽管代码的长度以及多个 for 循环都发出了代码气味,但它工作得很好,特别是我觉得我用来在列和值之间插入逗号的方法可以以不同的更好的方式完成。
public static int Insert(string source, string[] column, object[] values)
{
int rowsAffected = 0;
try
{
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
StringBuilder query = new StringBuilder();
query.Append(" INSERT INTO ");
query.Append(source);
query.Append("(");
for (int i = 0; i < column.Length; i++)
{
query.Append(column[i]);
if (i < values.Length - 1)
{
query.Append(",");
}
}
query.Append(")");
query.Append(" VALUES ");
query.Append("(");
for (int i = 0; i < values.Length; i++)
{
query.Append("@" + values[i].ToString());
if (i < values.Length - 1)
{
query.Append(",");
}
}
query.Append(")");
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand(query.ToString(), conn))
{
for (int i = 0; i < values.Length; i++)
{
cmd.Parameters.AddWithValue("@" + values[i].ToString(), values[i]);
}
rowsAffected = cmd.ExecuteNonQuery();
}
}
return rowsAffected;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return 0;
}
我正在使用System.Data.SQLite库与数据库进行交互。
感谢您的任何建议!