c# 向MySQL添加数据的两种方法

下面介绍两种执行SQL命令的方法,并作出相应地总结,第一种介绍一种常规用法,下面进行做简要地分析,首先我们需要执行打开数据库操作首先创建一个MySqlConnection对象,在其构造函数中传入一个连接字符串,然后执行Open操作打开数据库,在正确打开数据库之后我们才能进行相关的动作,在ExecuteSQL这个函数中,

我们执行MySqlCommand myCmd = new MySqlCommand(CmdString, conn),从而创建MySqlCommand对象,其中传入的两个参数分别为sql命令和第一步建立的MySqlConnection对象,然后执行int Cmd = myCmd.ExecuteNonQuery()这一句执行相应的命令,并返回受影响的行数,最后我们需要关闭数据库连接,并释放非托管资源,从而完成整个数据库操作的过程;这个是比较常规的一种做法,也是我们使用比较多的一种形式。

public class DataBaseMySqlHelper
{
    string connstr;
    MySqlConnection conn;
    //Server=xxxxxxx;Database=xxxxxxx;Uid=xxxxxxx;Pwd=xxxxxxx;CharSet=gbk;
    //Server=xxx.xx.xxx.xx;Database=MSUP;Uid=dvision;Pwd=dvision;Port=xxxx;allow zero datetime = true;
    MainWindow _MainWindow;
 
 
    public DataBaseMySqlHelper(MainWindow mainWindow)
    {
        _MainWindow = mainWindow;
         connstr = _MainWindow._ConfigInfo.MySqlConnectionStrings;        
    }
 
    public DataBaseMySqlHelper(MainWindow mainWindow, string connectionString)
    {
        _MainWindow = mainWindow;
        connstr = connectionString;
    }
 
    /// <summary>
    /// 打开数据库连接
    /// </summary>
    void Open()
    {
        try
        {
            conn = new MySqlConnection(connstr);
            conn.Open();
        }
        catch (Exception ex)
        {
 
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
         
    }
    /// <summary>
    /// 关闭数据库连接
    /// </summary>
    void Close()
    {
        conn.Close();
    }
 
    /// <summary>
    /// 返回影响数据库的行数            
    /// </summary>
    /// <param name="CmdString"></param>
    /// <returns></returns>
    public int ExecuteSQL(string CmdString)
    {
        try
        {
            Open();
            MySqlCommand myCmd = new MySqlCommand(CmdString, conn);
            int Cmd = myCmd.ExecuteNonQuery();
            Close();
            return Cmd;
        }
        catch (Exception ex)
        {
            _MainWindow.ShowErrorMessage(" MySql数据库查询失败!");
            return 0;
        }
    }
 
    /// <summary>
    /// 返回数据表
    /// </summary>
    /// <param name="CmdString"></param>
    /// <returns></returns>
    public DataTable GetDataTable(string CmdString)
    {
        try
        {
            Open();
            DataSet myDs = new DataSet();
            MySqlDataAdapter myDa = new MySqlDataAdapter();
            myDa.SelectCommand = new MySqlCommand(CmdString, conn);
            myDa.Fill(myDs);
            Close();
            return myDs.Tables[0];
        }
        catch (Exception e)
        {
            _MainWindow.ShowErrorMessage(" MySql数据库查询失败!");
            return null;
        }
    }
}

第二种方式,这里也贴出关键代码并做简要的分析:这里的关键是MySqlParameter[]数组的使用,我们在执行SQL语句的时候 DbHelperMySQL.ExecuteSql(strSql.ToString(),parameters);这里的parameters就是MySqlParameter[]数组,里面存储的是每个字段的数据,我们将在下面的代码中展示parameters的内容,

/// <summary>
        /// 增加一条数据
        /// </summary>
        public void Add(Maticsoft.Model.cameradetail model)
        {
            StringBuilder strSql=new StringBuilder();
            strSql.Append("insert into cameradetail_gis(");
            strSql.Append("EncodeDeviceUsername,MatrixIP,EncodeDevicePassword,id,Name,DisplayName,Location,Longitude,Latitude,CameraActive,ServerID,ForwardSvrIP,ForwardSvrPort,EncodeDeviceIP,EncodeDevicePort,CameraType,CameraModel,DeviceChannel,MatrixPort,MatrixChannelNum,VideoStoreServerIP,VideoStoreServerPort,VideoStoreServerUserID,VideoStoreServerPassword,EncodeDeviceModelNum,EncodeDeviceModelName,CameraInstallAddress,CameraStatus)");
            strSql.Append(" values (");
            strSql.Append("@EncodeDeviceUsername,@MatrixIP,@EncodeDevicePassword,@id,@Name,@DisplayName,@Location,@Longitude,@Latitude,@CameraActive,@ServerID,@ForwardSvrIP,@ForwardSvrPort,@EncodeDeviceIP,@EncodeDevicePort,@CameraType,@CameraModel,@DeviceChannel,@MatrixPort,@MatrixChannelNum,@VideoStoreServerIP,@VideoStoreServerPort,@VideoStoreServerUserID,@VideoStoreServerPassword,@EncodeDeviceModelNum,@EncodeDeviceModelName,@CameraInstallAddress,@CameraStatus)");
            MySqlParameter[] parameters = {
                    new MySqlParameter("@EncodeDeviceUsername", MySqlDbType.VarChar,64),
                    new MySqlParameter("@MatrixIP", MySqlDbType.VarChar,16),
                    new MySqlParameter("@EncodeDevicePassword", MySqlDbType.VarChar,64),
                    new MySqlParameter("@id", MySqlDbType.VarChar,14),
                    new MySqlParameter("@Name", MySqlDbType.VarChar,100),
                    new MySqlParameter("@DisplayName", MySqlDbType.VarChar,100),
                    new MySqlParameter("@Location", MySqlDbType.VarChar,250),
                    new MySqlParameter("@Longitude", MySqlDbType.VarChar,16),
                    new MySqlParameter("@Latitude", MySqlDbType.VarChar,16),
                    new MySqlParameter("@CameraActive", MySqlDbType.Int32,11),
                    new MySqlParameter("@ServerID", MySqlDbType.VarChar,16),
                    new MySqlParameter("@ForwardSvrIP", MySqlDbType.VarChar,16),
                    new MySqlParameter("@ForwardSvrPort", MySqlDbType.VarChar,16),
                    new MySqlParameter("@EncodeDeviceIP", MySqlDbType.VarChar,16),
                    new MySqlParameter("@EncodeDevicePort", MySqlDbType.VarChar,6),
                    new MySqlParameter("@CameraType", MySqlDbType.VarChar,6),
                    new MySqlParameter("@CameraModel", MySqlDbType.VarChar,6),
                    new MySqlParameter("@DeviceChannel", MySqlDbType.VarChar,12),
                    new MySqlParameter("@MatrixPort", MySqlDbType.VarChar,6),
                    new MySqlParameter("@MatrixChannelNum", MySqlDbType.VarChar,14),
                    new MySqlParameter("@VideoStoreServerIP", MySqlDbType.VarChar,16),
                    new MySqlParameter("@VideoStoreServerPort", MySqlDbType.VarChar,6),
                    new MySqlParameter("@VideoStoreServerUserID", MySqlDbType.VarChar,50),
                    new MySqlParameter("@VideoStoreServerPassword", MySqlDbType.VarChar,20),
                    new MySqlParameter("@EncodeDeviceModelNum", MySqlDbType.VarChar,6),
                    new MySqlParameter("@EncodeDeviceModelName", MySqlDbType.VarChar,50),
                    new MySqlParameter("@CameraInstallAddress", MySqlDbType.VarChar,250),
                    new MySqlParameter("@CameraStatus", MySqlDbType.Int32,11)};
            parameters[0].Value = model.EncodeDeviceUsername;
            parameters[1].Value = model.MatrixIP;
            parameters[2].Value = model.EncodeDevicePassword;
            parameters[3].Value = model.id;
            parameters[4].Value = model.Name;
            parameters[5].Value = model.DisplayName;
            parameters[6].Value = model.Location;
            parameters[7].Value = model.Longitude;
            parameters[8].Value = model.Latitude;
            parameters[9].Value = model.CameraActive;
            parameters[10].Value = model.ServerID;
            parameters[11].Value = model.ForwardSvrIP;
            parameters[12].Value = model.ForwardSvrPort;
            parameters[13].Value = model.EncodeDeviceIP;
            parameters[14].Value = model.EncodeDevicePort;
            parameters[15].Value = model.CameraType;
            parameters[16].Value = model.CameraModel;
            parameters[17].Value = model.DeviceChannel;
            parameters[18].Value = model.MatrixPort;
            parameters[19].Value = model.MatrixChannelNum;
            parameters[20].Value = model.VideoStoreServerIP;
            parameters[21].Value = model.VideoStoreServerPort;
            parameters[22].Value = model.VideoStoreServerUserID;
            parameters[23].Value = model.VideoStoreServerPassword;
            parameters[24].Value = model.EncodeDeviceModelNum;
            parameters[25].Value = model.EncodeDeviceModelName;
            parameters[26].Value = model.CameraInstallAddress;
            parameters[27].Value = model.CameraStatus;
 
            DbHelperMySQL.ExecuteSql(strSql.ToString(),parameters);
        }

这里我们重点来关注DbHelperMySQL.ExecuteSql(strSql.ToString(),parameters)这个函数,函数的源码如下:

这里面有一个重要的函数PrepareCommand(cmd, connection, null, SQLString, cmdParms),我们这里也贴出相应地源码,并做简要的分析:

这个函数首先是打开数据库连接,这里面最重要就是讲cmdParms里面的参数一个个添加到cmd.Parameters中,然后执行 int rows = cmd.ExecuteNonQuery();命令来执行相应的操作,这是一种决然不同的思路,我们在使用的时候可以考虑这两种方式来进行数据库的插入操作!

private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
            cmd.Connection = conn;
            cmd.CommandText = cmdText;
            if (trans != null)
                cmd.Transaction = trans;
            cmd.CommandType = CommandType.Text;//cmdType;
            if (cmdParms != null)
            {
                foreach (MySqlParameter parameter in cmdParms)
                {
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    cmd.Parameters.Add(parameter);
                }
            }
        }
 
        #endregion
/// <summary>
        /// 执行SQL语句,返回影响的记录数
        /// </summary>
        /// <param name="SQLString">SQL语句</param>
        /// <returns>影响的记录数</returns>
        public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                using (MySqlCommand cmd = new MySqlCommand())
                {
                    try
                    {
                        PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                        int rows = cmd.ExecuteNonQuery();
                        cmd.Parameters.Clear();
                        return rows;
                    }
                    catch (MySql.Data.MySqlClient.MySqlException e)
                    {
                        throw e;
                    }
                }
            }
        }
#region  执行简单SQL语句
 
     /// <summary>
     /// 执行SQL语句,返回影响的记录数
     /// </summary>
     /// <param name="SQLString">SQL语句</param>
     /// <returns>影响的记录数</returns>
     public static int ExecuteSql(string SQLString)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
             {
                 try
                 {
                     connection.Open();
                     int rows = cmd.ExecuteNonQuery();
                     return rows;
                 }
                 catch (MySql.Data.MySqlClient.MySqlException e)
                 {
                     connection.Close();
                     throw e;
                 }
             }
         }
     }
 
     public static int ExecuteSqlByTime(string SQLString, int Times)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
             {
                 try
                 {
                     connection.Open();
                     cmd.CommandTimeout = Times;
                     int rows = cmd.ExecuteNonQuery();
                     return rows;
                 }
                 catch (MySql.Data.MySqlClient.MySqlException e)
                 {
                     connection.Close();
                     throw e;
                 }
             }
         }
     }
    
     /// <summary>
     /// 执行MySql和Oracle滴混合事务
     /// </summary>
     /// <param name="list">SQL命令行列表</param>
     /// <param name="oracleCmdSqlList">Oracle命令行列表</param>
     /// <returns>执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功</returns>
     public static int ExecuteSqlTran(List<CommandInfo> list, List<CommandInfo> oracleCmdSqlList)
     {
         using (MySqlConnection conn = new MySqlConnection(connectionString))
         {
             conn.Open();
             MySqlCommand cmd = new MySqlCommand();
             cmd.Connection = conn;
             MySqlTransaction tx = conn.BeginTransaction();
             cmd.Transaction = tx;
             try
             {
                 foreach (CommandInfo myDE in list)
                 {
                     string cmdText = myDE.CommandText;
                     MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                     PrepareCommand(cmd, conn, tx, cmdText, cmdParms);
                     if (myDE.EffentNextType == EffentNextType.SolicitationEvent)
                     {
                         if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                         {
                             tx.Rollback();
                             throw new Exception("违背要求"+myDE.CommandText+"必须符合select count(..的格式");
                             //return 0;
                         }
                         object obj = cmd.ExecuteScalar();
                         bool isHave = false;
                         if (obj == null && obj == DBNull.Value)
                         {
                             isHave = false;
                         }
                         isHave = Convert.ToInt32(obj) > 0;
                         if (isHave)
                         {
                             //引发事件
                             myDE.OnSolicitationEvent();
                         }
                     }
                     if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                     {
                         if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                         {
                             tx.Rollback();
                             throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式");
                             //return 0;
                         }
 
                         object obj = cmd.ExecuteScalar();
                         bool isHave = false;
                         if (obj == null && obj == DBNull.Value)
                         {
                             isHave = false;
                         }
                         isHave = Convert.ToInt32(obj) > 0;
 
                         if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                         {
                             tx.Rollback();
                             throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0");
                             //return 0;
                         }
                         if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                         {
                             tx.Rollback();
                             throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0");
                             //return 0;
                         }
                         continue;
                     }
                     int val = cmd.ExecuteNonQuery();
                     if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                     {
                         tx.Rollback();
                         throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行");
                         //return 0;
                     }
                     cmd.Parameters.Clear();
                 }
                 string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC");
                 bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList);
                 if (!res)
                 {
                     tx.Rollback();
                     throw new Exception("执行失败");
                     // return -1;
                 }
                 tx.Commit();
                 return 1;
             }
             catch (MySql.Data.MySqlClient.MySqlException e)
             {
                 tx.Rollback();
                 throw e;
             }
             catch (Exception e)
             {
                 tx.Rollback();
                 throw e;
             }
         }
     }       
     /// <summary>
     /// 执行多条SQL语句,实现数据库事务。
     /// </summary>
     /// <param name="SQLStringList">多条SQL语句</param>    
     public static int ExecuteSqlTran(List<String> SQLStringList)
     {
         using (MySqlConnection conn = new MySqlConnection(connectionString))
         {
             conn.Open();
             MySqlCommand cmd = new MySqlCommand();
             cmd.Connection = conn;
             MySqlTransaction tx = conn.BeginTransaction();
             cmd.Transaction = tx;
             try
             {
                 int count = 0;
                 for (int n = 0; n < SQLStringList.Count; n++)
                 {
                     string strsql = SQLStringList[n];
                     if (strsql.Trim().Length > 1)
                     {
                         cmd.CommandText = strsql;
                         count += cmd.ExecuteNonQuery();
                     }
                 }
                 tx.Commit();
                 return count;
             }
             catch
             {
                 tx.Rollback();
                 return 0;
             }
         }
     }
 
     /// <summary>
     /// 执行带一个存储过程参数的的SQL语句。
     /// </summary>
     /// <param name="SQLString">SQL语句</param>
     /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
     /// <returns>影响的记录数</returns>
     public static int ExecuteSql(string SQLString, string content)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             MySqlCommand cmd = new MySqlCommand(SQLString, connection);
             MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
             myParameter.Value = content;
             cmd.Parameters.Add(myParameter);
             try
             {
                 connection.Open();
                 int rows = cmd.ExecuteNonQuery();
                 return rows;
             }
             catch (MySql.Data.MySqlClient.MySqlException e)
             {
                 throw e;
             }
             finally
             {
                 cmd.Dispose();
                 connection.Close();
             }
         }
     }
     /// <summary>
     /// 执行带一个存储过程参数的的SQL语句。
     /// </summary>
     /// <param name="SQLString">SQL语句</param>
     /// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
     /// <returns>影响的记录数</returns>
     public static object ExecuteSqlGet(string SQLString, string content)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             MySqlCommand cmd = new MySqlCommand(SQLString, connection);
             MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@content", SqlDbType.NText);
             myParameter.Value = content;
             cmd.Parameters.Add(myParameter);
             try
             {
                 connection.Open();
                 object obj = cmd.ExecuteScalar();
                 if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                 {
                     return null;
                 }
                 else
                 {
                     return obj;
                 }
             }
             catch (MySql.Data.MySqlClient.MySqlException e)
             {
                 throw e;
             }
             finally
             {
                 cmd.Dispose();
                 connection.Close();
             }
         }
     }
     /// <summary>
     /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例)
     /// </summary>
     /// <param name="strSQL">SQL语句</param>
     /// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
     /// <returns>影响的记录数</returns>
     public static int ExecuteSqlInsertImg(string strSQL, byte[] fs)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             MySqlCommand cmd = new MySqlCommand(strSQL, connection);
             MySql.Data.MySqlClient.MySqlParameter myParameter = new MySql.Data.MySqlClient.MySqlParameter("@fs", SqlDbType.Image);
             myParameter.Value = fs;
             cmd.Parameters.Add(myParameter);
             try
             {
                 connection.Open();
                 int rows = cmd.ExecuteNonQuery();
                 return rows;
             }
             catch (MySql.Data.MySqlClient.MySqlException e)
             {
                 throw e;
             }
             finally
             {
                 cmd.Dispose();
                 connection.Close();
             }
         }
     }
 
     /// <summary>
     ///执行一条计算查询结果语句,返回查询结果(object)。
     /// </summary>
     ///<param name="SQLString">计算查询结果语句</param>
     ///<returns>查询结果(object)</returns>
     public static object GetSingle(string SQLString)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
             {
                 try
                 {
                     connection.Open();
                     object obj = cmd.ExecuteScalar();
                     if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                     {
                         return null;
                     }
                     else
                     {
                         return obj;
                     }
                 }
                 catch (MySql.Data.MySqlClient.MySqlException e)
                 {
                     connection.Close();
                     throw e;
                 }
             }
         }
     }
     public static object GetSingle(string SQLString, int Times)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
             {
                 try
                 {
                     connection.Open();
                     cmd.CommandTimeout = Times;
                     object obj = cmd.ExecuteScalar();
                     if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                     {
                         return null;
                     }
                     else
                     {
                         return obj;
                     }
                 }
                 catch (MySql.Data.MySqlClient.MySqlException e)
                 {
                     connection.Close();
                     throw e;
                 }
             }
         }
     }
     /// <summary>
     /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
     /// </summary>
     /// <param name="strSQL">查询语句</param>
     /// <returns>MySqlDataReader</returns>
     public static MySqlDataReader ExecuteReader(string strSQL)
     {
         MySqlConnection connection = new MySqlConnection(connectionString);
         MySqlCommand cmd = new MySqlCommand(strSQL, connection);
         try
         {
             connection.Open();
             MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
             return myReader;
         }
         catch (MySql.Data.MySqlClient.MySqlException e)
         {
             throw e;
         }  
 
     }
     /// <summary>
     /// 执行查询语句,返回DataSet
     /// </summary>
     /// <param name="SQLString">查询语句</param>
     /// <returns>DataSet</returns>
     public static DataSet Query(string SQLString)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             DataSet ds = new DataSet();
             try
             {
                 connection.Open();
                 MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                 command.Fill(ds, "ds");
             }
             catch (MySql.Data.MySqlClient.MySqlException ex)
             {
                 throw new Exception(ex.Message);
             }
             return ds;
         }
     }
     public static DataSet Query(string SQLString, int Times)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             DataSet ds = new DataSet();
             try
             {
                 connection.Open();
                 MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
                 command.SelectCommand.CommandTimeout = Times;
                 command.Fill(ds, "ds");
             }
             catch (MySql.Data.MySqlClient.MySqlException ex)
             {
                 throw new Exception(ex.Message);
             }
             return ds;
         }
     }
 
 
 
     #endregion
 
     #region 执行带参数的SQL语句
 
     /// <summary>
     /// 执行SQL语句,返回影响的记录数
     /// </summary>
     /// <param name="SQLString">SQL语句</param>
     /// <returns>影响的记录数</returns>
     public static int ExecuteSql(string SQLString, params MySqlParameter[] cmdParms)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             using (MySqlCommand cmd = new MySqlCommand())
             {
                 try
                 {
                     PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                     int rows = cmd.ExecuteNonQuery();
                     cmd.Parameters.Clear();
                     return rows;
                 }
                 catch (MySql.Data.MySqlClient.MySqlException e)
                 {
                     throw e;
                 }
             }
         }
     }
 
 
     /// <summary>
     /// 执行多条SQL语句,实现数据库事务。
     /// </summary>
     /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
     public static void ExecuteSqlTran(Hashtable SQLStringList)
     {
         using (MySqlConnection conn = new MySqlConnection(connectionString))
         {
             conn.Open();
             using (MySqlTransaction trans = conn.BeginTransaction())
             {
                 MySqlCommand cmd = new MySqlCommand();
                 try
                 {
                     //循环
                     foreach (DictionaryEntry myDE in SQLStringList)
                     {
                         string cmdText = myDE.Key.ToString();
                         MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                         PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                         int val = cmd.ExecuteNonQuery();
                         cmd.Parameters.Clear();
                     }
                     trans.Commit();
                 }
                 catch
                 {
                     trans.Rollback();
                     throw;
                 }
             }
         }
     }
     /// <summary>
     /// 执行多条SQL语句,实现数据库事务。
     /// </summary>
     /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
     public static int ExecuteSqlTran(System.Collections.Generic.List<CommandInfo> cmdList)
     {
         using (MySqlConnection conn = new MySqlConnection(connectionString))
         {
             conn.Open();
             using (MySqlTransaction trans = conn.BeginTransaction())
             {
                 MySqlCommand cmd = new MySqlCommand();
                 try
                 { int count = 0;
                     //循环
                     foreach (CommandInfo myDE in cmdList)
                     {
                         string cmdText = myDE.CommandText;
                         MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                         PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                         
                         if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine)
                         {
                             if (myDE.CommandText.ToLower().IndexOf("count(") == -1)
                             {
                                 trans.Rollback();
                                 return 0;
                             }
 
                             object obj = cmd.ExecuteScalar();
                             bool isHave = false;
                             if (obj == null && obj == DBNull.Value)
                             {
                                 isHave = false;
                             }
                             isHave = Convert.ToInt32(obj) > 0;
 
                             if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
                             {
                                 trans.Rollback();
                                 return 0;
                             }
                             if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
                             {
                                 trans.Rollback();
                                 return 0;
                             }
                             continue;
                         }
                         int val = cmd.ExecuteNonQuery();
                         count += val;
                         if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0)
                         {
                             trans.Rollback();
                             return 0;
                         }
                         cmd.Parameters.Clear();
                     }
                     trans.Commit();
                     return count;
                 }
                 catch
                 {
                     trans.Rollback();
                     throw;
                 }
             }
         }
     }
     /// <summary>
     /// 执行多条SQL语句,实现数据库事务。
     /// </summary>
     /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
     public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List<CommandInfo> SQLStringList)
     {
         using (MySqlConnection conn = new MySqlConnection(connectionString))
         {
             conn.Open();
             using (MySqlTransaction trans = conn.BeginTransaction())
             {
                 MySqlCommand cmd = new MySqlCommand();
                 try
                 {
                     int indentity = 0;
                     //循环
                     foreach (CommandInfo myDE in SQLStringList)
                     {
                         string cmdText = myDE.CommandText;
                         MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Parameters;
                         foreach (MySqlParameter q in cmdParms)
                         {
                             if (q.Direction == ParameterDirection.InputOutput)
                             {
                                 q.Value = indentity;
                             }
                         }
                         PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                         int val = cmd.ExecuteNonQuery();
                         foreach (MySqlParameter q in cmdParms)
                         {
                             if (q.Direction == ParameterDirection.Output)
                             {
                                 indentity = Convert.ToInt32(q.Value);
                             }
                         }
                         cmd.Parameters.Clear();
                     }
                     trans.Commit();
                 }
                 catch
                 {
                     trans.Rollback();
                     throw;
                 }
             }
         }
     }
     /// <summary>
     /// 执行多条SQL语句,实现数据库事务。
     /// </summary>
     /// <param name="SQLStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
     public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList)
     {
         using (MySqlConnection conn = new MySqlConnection(connectionString))
         {
             conn.Open();
             using (MySqlTransaction trans = conn.BeginTransaction())
             {
                 MySqlCommand cmd = new MySqlCommand();
                 try
                 {
                     int indentity = 0;
                     //循环
                     foreach (DictionaryEntry myDE in SQLStringList)
                     {
                         string cmdText = myDE.Key.ToString();
                         MySqlParameter[] cmdParms = (MySqlParameter[])myDE.Value;
                         foreach (MySqlParameter q in cmdParms)
                         {
                             if (q.Direction == ParameterDirection.InputOutput)
                             {
                                 q.Value = indentity;
                             }
                         }
                         PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
                         int val = cmd.ExecuteNonQuery();
                         foreach (MySqlParameter q in cmdParms)
                         {
                             if (q.Direction == ParameterDirection.Output)
                             {
                                 indentity = Convert.ToInt32(q.Value);
                             }
                         }
                         cmd.Parameters.Clear();
                     }
                     trans.Commit();
                 }
                 catch
                 {
                     trans.Rollback();
                     throw;
                 }
             }
         }
     }
     /// <summary>
     /// 执行一条计算查询结果语句,返回查询结果(object)。
     /// </summary>
     /// <param name="SQLString">计算查询结果语句</param>
     /// <returns>查询结果(object)</returns>
     public static object GetSingle(string SQLString, params MySqlParameter[] cmdParms)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             using (MySqlCommand cmd = new MySqlCommand())
             {
                 try
                 {
                     PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                     object obj = cmd.ExecuteScalar();
                     cmd.Parameters.Clear();
                     if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                     {
                         return null;
                     }
                     else
                     {
                         return obj;
                     }
                 }
                 catch (MySql.Data.MySqlClient.MySqlException e)
                 {
                     throw e;
                 }
             }
         }
     }
 
     /// <summary>
     /// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
     /// </summary>
     /// <param name="strSQL">查询语句</param>
     /// <returns>MySqlDataReader</returns>
     public static MySqlDataReader ExecuteReader(string SQLString, params MySqlParameter[] cmdParms)
     {
         MySqlConnection connection = new MySqlConnection(connectionString);
         MySqlCommand cmd = new MySqlCommand();
         try
         {
             PrepareCommand(cmd, connection, null, SQLString, cmdParms);
             MySqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
             cmd.Parameters.Clear();
             return myReader;
         }
         catch (MySql.Data.MySqlClient.MySqlException e)
         {
             throw e;
         }
         //          finally
         //          {
         //              cmd.Dispose();
         //              connection.Close();
         //          }  
 
     }
 
     /// <summary>
     /// 执行查询语句,返回DataSet
     /// </summary>
     /// <param name="SQLString">查询语句</param>
     /// <returns>DataSet</returns>
     public static DataSet Query(string SQLString, params MySqlParameter[] cmdParms)
     {
         using (MySqlConnection connection = new MySqlConnection(connectionString))
         {
             MySqlCommand cmd = new MySqlCommand();
             PrepareCommand(cmd, connection, null, SQLString, cmdParms);
             using (MySqlDataAdapter da = new MySqlDataAdapter(cmd))
             {
                 DataSet ds = new DataSet();
                 try
                 {
                     da.Fill(ds, "ds");
                     cmd.Parameters.Clear();
                 }
                 catch (MySql.Data.MySqlClient.MySqlException ex)
                 {
                     throw new Exception(ex.Message);
                 }
                 return ds;
             }
         }
     }
 
 
     private static void PrepareCommand(MySqlCommand cmd, MySqlConnection conn, MySqlTransaction trans, string cmdText, MySqlParameter[] cmdParms)
     {
         if (conn.State != ConnectionState.Open)
             conn.Open();
         cmd.Connection = conn;
         cmd.CommandText = cmdText;
         if (trans != null)
             cmd.Transaction = trans;
         cmd.CommandType = CommandType.Text;//cmdType;
         if (cmdParms != null)
         {
             foreach (MySqlParameter parameter in cmdParms)
             {
                 if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                     (parameter.Value == null))
                 {
                     parameter.Value = DBNull.Value;
                 }
                 cmd.Parameters.Add(parameter);
             }
         }
     }
 
     #endregion
 }

以上就是c# 向MySQL添加数据的两种方法的详细内容,更多关于c# mysql添加数据的资料请关注我们其它相关文章!

(0)

相关推荐

  • C#在MySQL大量数据下的高效读取、写入详解

    前言 C#操作MySQL大量数据最常见的操作便是 select 读取数据,然后在C#中对数据进行处理, 完毕后再插入数据库中.  简而言之就 select -> process -> insert 三个步骤. 对于数据量小的情况下(百万级别 or 几百兆)可能 最多1个小时就处理完了.但是对于千万级数据可能几天,甚至更多. 那么问题来了,如何优化?? 第一步 解决读取的问题 跟数据库打交道的方式有很多,我来列举下吧: 1. [重武器-坦克大炮]使用重型ORM框架,比如 EF,NHibernat

  • C#中调用MySQL存储过程的方法

    本文实例讲述了C#中调用MySQL存储过程的方法.分享给大家供大家参考.具体如下: 这段代码演示在 C# 程序中调用 MySQL 的存储过程,没有返回值,没有参数传递. MySqlConnection myConnection; myConnection = new MySqlConnection(); myConnection.ConnectionString = "database="+database+";server="+ server+";use

  • C#实现MySQL命令行备份和恢复

    MySQL数据库的备份有很多工具可以使用,这两天写了一个使用C#调用MYSQL的mysqldump命令完成MySQL数据库的备份与恢复的小工具 先来说一下mysqldump命令备份MySQL数据库的使用方法 mysqldump -hhostname -uusername -ppassword databasename > backupfile.sql 直接将MySQL数据库压缩备份 mysqldump -hhostname -uusername -ppassword databasename |

  • C#连接MySQL的两个简单代码示例

    实现代码一.使用的是mysql自带的驱动安装一下即可 这是一个简单的例子. 在这里有个问题:dataset如果没设主键的话,可能会引起一些对数库操作的问题,比如会造成updata出现错误. static void Main(string[] args) { string sqlstr = "select * from manavatar"; MySQLConnection DBConn = new MySQLConnection(new MySQLConnectionString(&q

  • c#几种数据库的大数据批量插入(SqlServer、Oracle、SQLite和MySql)

    在之前只知道SqlServer支持数据批量插入,殊不知道Oracle.SQLite和MySql也是支持的,不过Oracle需要使用Orace.DataAccess驱动,今天就贴出几种数据库的批量插入解决方法. 首先说一下,IProvider里有一个用于实现批量插入的插件服务接口IBatcherProvider,此接口在前一篇文章中已经提到过了. /// <summary> /// 提供数据批量处理的方法. /// </summary> public interface IBatch

  • C#连接MySQL操作详细教程

    C#如何连接MySQL进行操作,供大家参考,具体内容如下 1.引入MySql.Data.dll 例如小编是vs2017,创建工程之后,添加应用,选择工程,点击下面的引用,右击打开,选择添加引用 2.如何找到自己的MySql.Data.dll,答案就是自己安装MySQL的安装路径下,找到后选择添加 3.就是直接贴代码了,这里是查询账号密码,以及插入账号密码(注意:更改个人的数据名字以及表密码等) using System; using System.Collections.Generic; usi

  • C#如何连接MySQL数据库

    本文章是建立在已经安装MySQL数据库的前提,默认安装在C:\Program Files (x86)\MySQL,建议在安装时选中Connector.NET 6.9的安装,里面有MySQL与C#连接的动态链接库. 帮助文档C:\Program Files (x86)\MySQL\Connector.NET 6.9\Documentation\ConnectorNET.chm是我撰写此文章的主要依据.其中Users Guide下,Programming是对动态链接库8个类的介绍,Tutorial是

  • C#实现操作MySql数据层类MysqlHelper实例

    本文实例讲述了C#实现操作MySql数据层类MysqlHelper.分享给大家供大家参考.具体如下: using System; using System.Data; using System.Configuration; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using MySql.Data; using MySql.Data.MySqlCli

  • C#如何在海量数据下的高效读取写入MySQL

    前提 由于工作的原因,经常需要对海量数据进行处理,做的数据爬虫相关,动辄千万级别的数据,单表几十个G都是都是家常便饭.  主要开发语言是C#,数据库使用的是MySQL. 最常见的操作便是 select 读取数据,然后在C#中对数据进行处理, 完毕后再插入数据库中.  简而言之就 select -> process -> insert三个步骤. 对于数据量小的情况下(百万级别 or 几百兆)可能最多1个小时就处理完了.但是对于千万级数据可能几天,甚至更多. 那么问题来了,如何优化?? (数据库的

  • C#连接mysql的方法【基于vs2010】

    本文实例讲述了C#连接mysql的方法.分享给大家供大家参考,具体如下: 在vs2010中  工具->数据库连接   里要想连接到MySQL数据库,需要安装这样一个东西: MySql Connector: 1.首先安装 connector .下载地址:(http://www.mysql.com/downloads/connector/net/) 2.现在就可以了,打开vs2010试试吧! 安装完成后找到安装目录下(C:\Program Files\MySQL\MySQL Connector Ne

  • C#连接mysql数据库完整实例

    本文实例讲述了C#连接mysql数据库的方法.分享给大家供大家参考.具体实现方法如下: using System; using System.Configuration; using MySql.Data.MySqlClient; /// <summary> /// TestDatebase 的摘要说明 /// </summary> public class TestDatebase { public TestDatebase() { // // TODO: 在此处添加构造函数逻辑

随机推荐