class MysqlClass
{
private MySqlConnection SqlConn;
public MysqlClass(string ServerIp,string Port, string SQLUserName, string SQLUserPass, string DataBase)
{
this.SqlConn = new MySqlConnection(MysqlClass.MsSqlConn(ServerIp,Port, SQLUserName, SQLUserPass, DataBase));
}
private static string MsSqlConn(string strIp,string Port, string UserId, string Pwd, string DataName)
{
return string.Concat(new string[]
{
"server =",
strIp,
";port = ",
Port,
";user = ",
UserId,
";password=",
Pwd,
";database =",
DataName,
";"
});
}
public int ExecuteNonQuery(string sql)
{
MySqlCommand sqlCommand = new MySqlCommand(sql, this.SqlConn);
int result;
try
{
this.SqlConn.Open();
sqlCommand.CommandTimeout = 60;
result = sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
MySqlConnection.ClearPool(this.SqlConn);
result = 0;
}
finally
{
this.SqlConn.Close();
}
return result;
}
public object ExecuteScalar(string sql)
{
MySqlCommand sqlCommand = new MySqlCommand(sql, this.SqlConn);
object result;
try
{
this.SqlConn.Open();
sqlCommand.CommandTimeout = 60;
result = sqlCommand.ExecuteScalar();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
MySqlConnection.ClearPool(this.SqlConn);
result = null;
}
finally
{
this.SqlConn.Close();
}
return result;
}
public DataTable GetDataTable(string sql)
{
DataTable dataTable = new DataTable();
DataTable result;
try
{
this.SqlConn.Open();
MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(sql, this.SqlConn);
sqlDataAdapter.Fill(dataTable);
result = dataTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
MySqlConnection.ClearPool(this.SqlConn);
result = null;
}
finally
{
this.SqlConn.Close();
}
return result;
}
public bool ExecuteNonQueryByTransaction(List<string> SQLStringList)
{
MySqlCommand sqlCommand = new MySqlCommand();
this.SqlConn.Open();
sqlCommand.Connection = this.SqlConn;
MySqlTransaction sqlTransaction = this.SqlConn.BeginTransaction();
sqlCommand.Transaction = sqlTransaction;
bool result;
try
{
for (int i = 0; i < SQLStringList.Count; i++)
{
string text = SQLStringList[i].ToString();
if (text.Trim().Length > 1)
{
sqlCommand.CommandText = text;
sqlCommand.ExecuteNonQuery();
}
}
sqlTransaction.Commit();
result = true;
}
catch (Exception ex)
{
sqlTransaction.Rollback();
MySqlConnection.ClearPool(this.SqlConn);
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
result = false;
}
finally
{
this.SqlConn.Close();
}
return result;
}