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

更新时间:2023-07-05 09:56:46 阅读: 评论:0

c#向MySQL添加数据的两种⽅法
下⾯介绍两种执⾏SQL命令的⽅法,并作出相应地总结,第⼀种介绍⼀种常规⽤法,下⾯进⾏做简要地分析,⾸先我们需要执⾏打开数据库操作⾸先创建⼀个MySqlConnection对象,在其构造函数
中传⼊⼀个连接字符串,然后执⾏Open操作打开数据库,在正确打开数据库之后我们才能进⾏相关的动作,在ExecuteSQL这个函数中,
我们执⾏MySqlCommand myCmd = new MySqlCommand(CmdString, conn),从⽽创建MySqlCommand对象,其中传⼊的两个参数分别为sql命令和第⼀步建⽴的MySqlConnection对象,然后执⾏
int Cmd = myCmd.ExecuteNonQuery()这⼀句执⾏相应的命令,并返回受影响的⾏数,最后我们需要关闭数据库连接,并释放⾮托管资源,从⽽完成整个数据库操作的过程;这个是⽐较常规的⼀种做法,
也是我们使⽤⽐较多的⼀种形式。
public class DataBaMySqlHelper
{
最好的翻译软件
string connstr;
MySqlConnection conn;
//Server=xxxxxxx;Databa=xxxxxxx;Uid=xxxxxxx;Pwd=xxxxxxx;CharSet=gbk;
//;Databa=MSUP;Uid=dvision;Pwd=dvision;Port=xxxx;allow zero datetime = true;
MainWindow _MainWindow;
public DataBaMySqlHelper(MainWindow mainWindow)
{
_MainWindow = mainWindow;
connstr = _MainWindow._ConfigInfo.MySqlConnectionStrings;
}
public DataBaMySqlHelper(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 Clo()
{
conn.Clo();
}
/// <summary>
/// 返回影响数据库的⾏数
/// </summary>
/// <param name="CmdString"></param>
/// <returns></returns>
public int ExecuteSQL(string CmdString)
{
pkatry
{
Open();
MySqlCommand myCmd = new MySqlCommand(CmdString, conn);
int Cmd = myCmd.ExecuteNonQuery();
Clo();
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);
Clo();
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("inrt into cameradetail_gis(");
strSql.Append("EncodeDeviceUrname,MatrixIP,EncodeDevicePassword,id,Name,DisplayName,Location,Longitude,Latitude,CameraActive,ServerID,ForwardSvrIP,ForwardSvrPort,EncodeDeviceIP,EncodeDevicePort,CameraType,CameraModel,Devic            strSql.Append(" values (");
strSql.Append("@EncodeDeviceUrname,@MatrixIP,@EncodeDevicePassword,@id,@Name,@DisplayName,@Location,@Longitude,@Latitude,@CameraActive,@ServerID,@ForwardSvrIP,@ForwardSvrPort,@EncodeDeviceIP,@EncodeDevicePort,            MySqlParameter[] parameters = {
new MySqlParameter("@EncodeDeviceUrname", MySqlDbType.VarChar,64),
new MySqlParameter("@MatrixIP", MySqlDbType.VarChar,16),
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("@VideoStoreServerUrID", 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.EncodeDeviceUrname;
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.VideoStoreServerUrID;
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>
{
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.Clo();
throw e;
}
}
}
}
public static int ExecuteSqlByTime(string SQLString, int Times)
2012年6月四级答案
{
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.Clo();
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)
{
instanttx.Rollback();
throw new Exception("违背要求"+myDE.CommandText+"必须符合lect count(..的格式");
//return 0;
}
object obj = cmd.ExecuteScalar();
bool isHave = fal;
if (obj == null && obj == DBNull.Value)
{
isHave = fal;
}
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 + "必须符合lect count(..的格式");
//return 0;
}
object obj = cmd.ExecuteScalar();
bool isHave = fal;
if (obj == null && obj == DBNull.Value)
{
isHave = fal;
}
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))
update rvice{
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;
}
interpretation
finally
{
cmd.Dispo();
connection.Clo();
}
}
}
/// <summary>
/// 执⾏带⼀个存储过程参数的的SQL语句。
/// </summary>
/// <param name="SQLString">SQL语句</param>
hydrogenated/// <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;
}
el
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
finally
{
cmd.Dispo();
connection.Clo();
}
}
}
/// <summary>
/// 向数据库⾥插⼊图像格式的字段(和上⾯情况类似的另⼀种实例)
/// </summary>
/// <param name="strSQL">SQL语句</param>
/// <param name="fs">图像字节,数据库的字段类型为image的情况</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSqlInrtImg(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.Dispo();
connection.Clo();
}
}
}
/// <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;
}
el
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Clo();
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;
}
el
{
return obj;
}
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
connection.Clo();
throw e;
}
}
进球英语}
}
/// <summary>
/// 执⾏查询语句,返回MySqlDataReader ( 注意:调⽤该⽅法后,⼀定要对MySqlDataReader进⾏Clo )
/// </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.CloConnection);
return myReader;
}
catch (MySql.Data.MySqlClient.MySqlException e)
{
throw e;
}
}
/// <summary>
/// 执⾏查询语句,返回DataSet

本文发布于:2023-07-05 09:56:46,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/90/167718.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数据库   语句   查询   返回   打开   连接   字段
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图