usingMySql.Data.MySqlClient;usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespacemysql_nf
{classMysql_Helper
{privateMySqlConnection myConnection;privateMySqlCommand myCommand;privateMySqlDataAdapter myAdapter;privateMySqlTransaction myTransaction;string str_Con = "data source=172.20.168.210;user id=root;pwd=QSMC+12345;initial catalog=jinwei;allow zero datetime=true";//建立DB连接
publicMysql_Helper()
{string contString =str_Con;try{
myConnection= newMySqlConnection();
myConnection.ConnectionString=contString;
myConnection.Open();
}catch(Exception ex)
{
Console.WriteLine(ex);
MessageBox.Show("连接失败!");
}finally{
myConnection.Close();
}
}//数据查询操作
publicDataTable executeQuery(String sql)
{
DataTable myTable;try{
myCommand=myConnection.CreateCommand();
myCommand.CommandText=sql;
myAdapter= newMySqlDataAdapter(myCommand);
DataSet mySet= newDataSet();
myAdapter.Fill(mySet,"selectDa");
myTable= mySet.Tables["selectDa"];returnmyTable;
}catch(Exception ex)
{throwex;
}finally{
myConnection.Close();
}
}//数据插入,删除,更新操作
publicBoolean executeUpdate(String sql)
{try{
myCommand=myConnection.CreateCommand();
myCommand.CommandText=sql;
myCommand.ExecuteNonQuery();if (myTransaction == null)
{
myConnection.Close();
myConnection= null;
}return true;
}catch(Exception ex)
{if (myTransaction != null)
{
myTransaction.Rollback();
myTransaction= null;
MessageBox.Show("数据发生错误,正在启用事务回滚!");
}else if (myConnection == null)
{
MessageBox.Show("请启用事务!");
}else{
MessageBox.Show("发生错误!");
}
Console.WriteLine(ex);return false;
}finally{
myConnection.Close();
}
}//创建事务
public voidcreateTransaction()
{try{
myTransaction=myConnection.BeginTransaction();
}catch(Exception ex)
{throwex;
}finally{
myConnection.Close();
}
}//提交事务
public voidcommitTransaction()
{try{if (myTransaction != null) myTransaction.Commit();
}catch(Exception ex)
{throwex;
}finally{
myConnection.Close();
myConnection= null;
}
}
}
}