MySQL - >交易背景 - >代码审查

时间:2016-04-06 19:42:13

标签: c# mysql

我希望有人可以查看我如何使用Transaction with MySql的上下文。我认为这应该适用于下面的大纲。有人可以查看我的代码并告诉我,如果我正确地做到了吗?谢谢。

我相信这应该:

  • 实例化数据库连接。
  • 遍历给定DataTable的DataTable行。
  • 检查表是否存在,如果不存在,则执行Create Table。
  • 使用信息参数执行Insert命令到新创建的或现有的表中。
  • 提交事务,然后关闭连接。

        //Open the SQL Connection
        var dbConnection = new MySqlConnection(GetConnectionString(WowDatabase));
        dbConnection.Open();
        //Instantiate the Command
        using (var cmd = new MySqlCommand())
        {
            //Create a new Transaction
            using (var transaction = dbConnection.BeginTransaction())
            {
                uint lastId = 999999;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //var identifier = dt.Rows[i].Field<int>("Identifier");
                    var id = dt.Rows[i].Field<uint>("Entry");
                    var name = dt.Rows[i].Field<string>("Name");
                    var zone = dt.Rows[i].Field<uint>("ZoneID");
                    var map = dt.Rows[i].Field<uint>("MapID");
                    var state = dt.Rows[i].Field<Enums.ItemState>("State");
                    var type = dt.Rows[i].Field<Enums.ObjectType>("Type");
                    var faction = dt.Rows[i].Field<Enums.FactionType>("Faction");
                    var x = dt.Rows[i].Field<float>("X");
                    var y = dt.Rows[i].Field<float>("Y");
                    var z = dt.Rows[i].Field<float>("Z");
                    string dataTableName = "entry_" + id;
                    //Create Table if it does not exist.
                    if (id != lastId)
                    {
                        cmd.CommandText = $"CREATE TABLE IF NOT EXISTS `{dataTableName}` (" +
                                          "`identifier`   int NOT NULL AUTO_INCREMENT COMMENT 'Auto Incriment Identifier' ," +
                                          "`zone_id`      int NULL COMMENT 'Zone Entry' ," +
                                          "`x_axis`       float NULL COMMENT 'X Axis on Map' ," +
                                          "`y_axis`       float NULL COMMENT 'Y Axis on Map' ," +
                                          "`z_axis`       float NULL COMMENT 'Z Axis on Map' ," +
                                          "`situation`    enum('') NULL COMMENT 'Location of the item. Underground, Indoors, Outdoors)' ," +
                                          "`faction`      enum('') NULL COMMENT 'Specifies the Faction which can safely access the item.' ," +
                                          "PRIMARY KEY(`identifier`)" +
                                          ")";
                        cmd.ExecuteNonQuery();
                        lastId = id;
                    }
                    //Create command to execute the insertion of Data into desired Table
                    cmd.CommandText = $"INSERT INTO [{dataTableName}] " +
                                           "([identifier], [zone_id], [x_axis], [y_axis], [z_axis], [situation], [faction], [Create_Date], [Update_Date]) " +
                                           "VALUES (@Identifier, @Zone_Id, @X_Axis, @Y_Axis, @Z_Axis, @Situation, @Faction, @Create_Date, @Update_Date)";
                    //Add data value with Parameters.
                    cmd.CommandType = CommandType.Text;
                    //cmd.Parameters.AddWithValue("@Identifier", identifier);
                    cmd.Parameters.AddWithValue("@Identifier", id);
                    cmd.Parameters.AddWithValue("@Zone_Id", zone);
                    cmd.Parameters.AddWithValue("@X_Axis", x);
                    cmd.Parameters.AddWithValue("@Y_Axis", y);
                    cmd.Parameters.AddWithValue("@Z_Axis", z);
                    cmd.Parameters.AddWithValue("@Situation", state);
                    cmd.Parameters.AddWithValue("@Faction", faction);
                    cmd.Parameters.AddWithValue("@Create_Date", DateTime.Now.Date);
                    cmd.Parameters.AddWithValue("@Update_Date", DateTime.Now.Date);
    
                    cmd.ExecuteNonQuery();
                } //for (int i = 0; i < dt.Rows.Count; i++)
    
                //Commit the Transaction
                transaction.Commit();
            } //using (var transaction = dbConnection.BeginTransaction())
        } //using (var cmd = new MySqlCommand())
    
        //Close the Connection
        dbConnection.Close();
    

2 个答案:

答案 0 :(得分:1)

我认为这对MySql不起作用(如预期的那样)。有一些语句会导致隐式提交 - CREATE TABLE就是其中之一。

http://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html

答案 1 :(得分:0)

考虑using声明

您实际上可以将现有dbConnection包装在using语句中,以确保安全处置它(类似于处理事务,命令等的方式):

 //Open the SQL Connection
 using(var dbConnection = new MySqlConnection(GetConnectionString(WowDatabase))
 {
      // Other code omitted for brevity
 }

一致的字符串插值

你有几个地方只是通过+连接字符串,但你大多利用C#6的字符串插值功能。您可能想考虑在任何地方使用它:

 string dataTableName = $"entry_{id}";

无需设置CommandType

此外,您可以删除实际CommandType对象的cmd属性设置,因为CommandType.Text是默认设置:

 //cmd.CommandType = CommandType.Text;