I am trying to commit to my database and I am receiving an exception stating that is not open when I try to Execute Query. Can anyone explain what I am doing wrong here? GetConnectionString(DbMap)
definitely does return the correct string as I am using it to create tables prior to this code execution.
public static void InsertDataTable(DataTable dt)
{
try
{
//Open the SQL Connection
using (var dbConnection = new MySqlConnection(GetConnectionString(DbMap)))
{
dbConnection.Open();
//Instantiate the Command
using (var cmd = new MySqlCommand())
{
//Create a new Transaction
using (var transaction = dbConnection.BeginTransaction())
{
for (int i = 0; i < dt.Rows.Count; i++)
{
//var identifier = dt.Rows[i].Field<int>("Identifier");
var entry = dt.Rows[i].Field<uint>("Entry");
var name = dt.Rows[i].Field<string>("Name");
var zone = dt.Rows[i].Field<uint>("Zone");
var type = dt.Rows[i].Field<ObjectType>("Type");
//Add data value with Parameters.
cmd.Parameters.AddWithValue("@Entry", entry);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Type", type);
//Create command to execute the insertion of Data into desired Table
string dataTableName = "zone_" + zone;
cmd.CommandText = $"INSERT INTO [{dataTableName}] " +
"([entry], [name], [type]) " +
"VALUES (@Entry, @Name, @Type)";
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();
}
}
catch (MySqlException ex)
{
Logger.Write("InsertDataTable | MySqlException: " + ex);
}
catch (Exception ex)
{
Logger.Write("InsertDataTable | Exception: " + ex);
}
}