簡體   English   中英

將字符串從MSSQL轉換為MySQL

[英]Converting string from MSSQL to MySQL

我有一個正在從SQL DB讀取並寫入MySQL的應用程序。 該應用程序用於為客戶端遷移數據。 在測試時,我遇到一個記錄問題,並且感到很困惑。 我已經使用C# Encoding類測試了該站點的各種建議,並且每次都嘗試對它進行轉換,但都沒有成功。

該SQL排序規則是SQL_Latin1_General_CP1_CI_AS MySQL的核對是latin1_general_ci的代碼(在一個樣品foreach循環)如下:

foreach(var pgObj in PgObjList)
{
    //byte[] bytes = Encoding.Default.GetBytes(pgObj.Description);
    //pgObj.Description = Encoding.ASCII.GetString(bytes);

    byte[] utf8Bytes = Encoding.UTF8.GetBytes(pgObj.Description);
    byte[] isoBytes = Encoding.Convert(Encoding.ASCII, Encoding.UTF8, utf8Bytes);
    string uf8converted = Encoding.UTF8.GetString(isoBytes);

    string insertSQL = @"INSERT INTO `mainsite`.`sf_root_items` 
                        (`ID`, 
                        `LoweredName`, 
                        `MenuName`, 
                        `Title`, 
                        `Description`, 
                        `PageType`, 
                        `ExternalUrl`
                        )
                        VALUES
                        ('" + pgObj.ID + @"', 
                        '" + pgObj.LoweredName + @"', 
                        '" + pgObj.MenuName + @"', 
                        '" + pgObj.Title + @"', 
                        '" + pgObj.Description + @"', 
                        '" + pgObj.PageType + @"', 
                        '" + pgObj.ExternalUrl + @"'
                        );";
    string outputMsg;
    // more code here to execute the MySQL statement
}

我得到的最好結果是轉換為ASCII碼(帶注釋的代碼),並將文本存儲在看起來像漢字的位置。 沒有異常,但是當我以任何其他方式運行它時,此記錄將導致異常。

例外:

MySQL Exception on record#28/r/n
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'il vous plaît (RSVP)', 
                                                '0', 
             ' at line 15
       at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
       at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
       at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
       at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
       at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
       at SharepointImportDL.SharepointContentImport.GetSitefinityContent.addRootItems(List`1 PgObjList, String WPConnectionString) in C:\Users\Administrator\Source\Repos\TestBinaryWriter\Test Binary Writer\SharepointImportDL\SharepointContentImport\GetSitefinityContent.cs:line 986

第986行是SQL執行: int output = cmd.ExecuteNonQuery();

可能還值得注意的是,我要插入的字符串來自nvarchar列(MSSQL)和varchar(MySQL)列

具有諷刺意味的是,該字符串是一個簡單的“Répondezs'il vousplaît(RSVP)” (我想打要使用法語文本的自命不凡的人),因此不太可能再次遇到它,但顯然我需要處理這種可能性。

逃逸字符串(例如, pgObj.Description構建SQL(前) string insertSQL )。 否則您會從類似的東西中得到語法錯誤

, 'Répondez s'il vous plaît (RSVP)', 

請注意在單引號內如何有一個單引號? 還要注意錯誤是如何指出問題的:

... syntax to use near 'il vous plaît (RSVP)', 

感謝Palle Due建議使用參數化查詢,我決定在MySQL中編寫一個存儲過程來處理這些問題。

基於我的原始問題,我的C#代碼如下:

foreach(var pgObj in PgObjList)
{
    string SP = "sp_insert_root_items";
    string outputMsg = "";

    MySqlConnection myConnection = new MySqlConnection(WPConnectionString);
    MySqlCommand cmd;
    try
    {
        if (myConnection.State != ConnectionState.Open)
        {
            myConnection.Close();
            myConnection.Open();
        }
        cmd = myConnection.CreateCommand();
        cmd.CommandText = SP;
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@ID", pgObj.ID);
        cmd.Parameters["@ID"].Direction = ParameterDirection.Input;

        cmd.Parameters.AddWithValue("@LoweredName", pgObj.LoweredName);
        cmd.Parameters["@LoweredName"].Direction = ParameterDirection.Input;

        cmd.Parameters.AddWithValue("@MenuName", pgObj.MenuName);
        cmd.Parameters["@MenuName"].Direction = ParameterDirection.Input;

        cmd.Parameters.AddWithValue("@Title", pgObj.Title);
        cmd.Parameters["@Title"].Direction = ParameterDirection.Input;

        cmd.Parameters.AddWithValue("@Description", pgObj.Description);
        cmd.Parameters["@Description"].Direction = ParameterDirection.Input;

        cmd.Parameters.AddWithValue("@PageType", pgObj.PageType);
        cmd.Parameters["@PageType"].Direction = ParameterDirection.Input;

        cmd.Parameters.AddWithValue("@ExternalUrl", pgObj.ExternalUrl);
        cmd.Parameters["@ExternalUrl"].Direction = ParameterDirection.Input;

        cmd.Parameters.AddWithValue("@ParentID", "");
        cmd.Parameters["@ParentID"].Direction = ParameterDirection.Input;

        int output = cmd.ExecuteNonQuery();

        // a value greater than 0 means execution was successful
        if (output > 0)
        {
            counter++;
            //outputMsg = "Record #" + counter.ToString() + " created";

        }
        else
        {
            counter++;
            outputMsg = "There was an error inserting record #" + counter.ToString();
        }

        myConnection.Close();
    }
    catch (Exception ex)
    {
        outputMsg = "MySQL Exception on record#" + counter.ToString() + "/r/n" + ex.ToString();
    }

    returnMsg += outputMsg;

}

下面是存儲過程的一個示例-它是從SQLYog導出的。

DELIMITER $$

/*!50003 CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_insert_root_items`(
        IN ID VARCHAR(255), 
        IN LoweredName VARCHAR(255), 
        IN MenuName VARCHAR(255), 
        IN Title VARCHAR(255), 
        IN Description VARCHAR(500), 
        IN PageType VARCHAR(255), 
        IN ExternalUrl VARCHAR(255), 
        IN ParentID VARCHAR(255)
    )
BEGIN
    INSERT INTO `wp_sf_page_items`
        (`ID`, 
        `LoweredName`, 
        `MenuName`, 
        `Title`, 
        `Description`, 
        `PageType`, 
        `ExternalUrl`, 
        `ParentID`
    )
    VALUES(ID, LoweredName, MenuName, Title, Description, PageType, ExternalUrl, ParentID);  
END */$$
DELIMITER ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM