[英]Inserting multiple records into MySQL using MySqlCommand in one query C# (MySQLConnector) & command Parameters for escaping quotes
我試圖使用C#中的MySqlCommand
對象(使用MySQL Connector庫)在一個查詢中將多個記錄插入到表中。
我知道如何做到這一點的唯一方法是自己動態構建查詢並設置command.CommandType = CommandType.Text;
此方法的問題是字段不會轉義為引號等。 我可以自己編寫一個函數來逃避這些值,但是我在互聯網上看到的每篇文章或問題似乎都對此command.Parameters
,並說使用command.Parameters
。參數更加高效和徹底。
我的問題是我不知道如何設置多行的參數。 我怎樣才能做到這一點?
編輯 :這是一個24/7運行的商業服務,所以我需要找到最有效的方法來執行此操作。 我沒有使用存儲過程 - 這是唯一的方式還是另一種方式?
public static string MySqlEscape(object value)
{
string val = value.ToString();
if (val.Contains("'"))
return val.Replace("'", "' + NCHAR(96) + '");
else
return val;
}
public void InsertProcessedData(long unprocessedID, long pagerID, long firmwareRelativeProtocolID, DataTable processedData)
{
using(processedData)
{
string paramColNames = string.Empty;
for(int i =1;i<=processedData.Columns.Count;i+=1)
{
paramColNames+=string.Format("Param{0}",i);
if(i!=processedData.Columns.Count)
paramColNames+=",";
}
string SQL = "INSERT INTO gprs_data_processed (@UnprocessedID,@PagerID,@FirmwareRelativeProtocolID,"+paramColNames+") VALUES ";
for (int i = 0; i < processedData.Rows.Count;i+=1)
{
SQL += string.Format("({0},{1},{2},", unprocessedID, pagerID, firmwareRelativeProtocolID);
for (int c = 0; c < processedData.Columns.Count; c += 1)
{
SQL += string.Format("'{0}'", MySqlEscape(processedData.Rows[i][c]));
if (i != processedData.Columns.Count)
SQL += ",";
}
SQL+=")";
if (i + 1 != processedData.Rows.Count)
SQL += ",";
else
SQL += ";";
}
using (MySqlConnection connection = new MySqlConnection(_connection))
{
connection.Open();
using (MySqlCommand command = connection.CreateCommand())
{
command.CommandType = CommandType.Text;
command.CommandText = SQL;
command.ExecuteNonQuery();
}
connection.Close();
}
}
}
我不確定如何創建單個命令。 我所做的是創建一個使用參數的方法,然后傳入我想一次運行一個的值。
我的方法:
public void Insert(string strSQL, string[,] parameterValue)
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(strSQL, connection);
//add parameters
for (int i = 0; i < (parameterValue.Length / 2); i++)
{
cmd.Parameters.AddWithValue(parameterValue[i, 0], parameterValue[i, 1]);
}
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
我最終只使用了我已編寫的函數,因為它在一個命令中完成所有操作,並使用:
public static string MySqlEscape(object value)
{
string val = value.ToString();
if (val.Contains("'"))
return val.Replace("'", "''");
else
return val;
}
它工作正常,所以我會看到事情的進展。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.