VisualStudio 连接 MySql 实现增删查改
首先创建数据库,建立一个用户登录表
2、visualStudio默认是不支持MySql的,要想通过Ado.Net 操作MySql
需要在管理NeGet包添加对MySql.Data 和 MySql.Data.Entity的引用
3、在app.Config中添加数据库连接信息
4、前端页面代码:
<WrapPanel>
<Button Content="是否存在" Name="IsExitBtn" Click="IsExitBtn_Click"
Width="" Height="" ></Button>
<Button Content="新增" Name="AddBtn" Click="AddBtn_Click"
Width="" Height=""></Button>
<Button Content="修改" Name="UpdateBtn" Click="UpdateBtn_Click"
Width="" Height=""></Button>
<Button Content="删除" Name="DelBtn" Click="DelBtn_Click"
Width="" Height=""></Button>
<Button Content="批量删除" Name="BatchDelBtn" Click="BatchDelBtn_Click"
Width="" Height=""></Button>
<Button Content="批量获取" Name="BatchGetListBtn" Click="BatchGetListBtn_Click"
Width="" Height="" ></Button>
</WrapPanel>
5、cs后台代码:
private void AddBtn_Click(object sender, RoutedEventArgs e)
{
#region 新增
StringBuilder addStrSql = new StringBuilder();
addStrSql.Append("insert into LoginUser(");
addStrSql.Append("UserId,Name,Age)");
addStrSql.Append(" values (");
addStrSql.Append("@UserId,@Name,@Age)"); MySqlParameter[] parameters = {
new MySqlParameter("@UserId", ),
new MySqlParameter("@Name", "张三"),
new MySqlParameter("@Age", )};
var add = new CaseUserData().Add(addStrSql.ToString(), parameters);
#endregion
} private void UpdateBtn_Click(object sender, RoutedEventArgs e)
{
#region 修改
StringBuilder updateStrSql = new StringBuilder();
updateStrSql.Append("update LoginUser set ");
updateStrSql.Append("Name=@Name,");
updateStrSql.Append("Age=@Age");
updateStrSql.Append(" WHERE UserId=@UserId");
MySqlParameter[] uparameters = {
new MySqlParameter("@UserId", ),
new MySqlParameter("@Name", "王五"),
new MySqlParameter("@Age", ) };
var update = new CaseUserData().Update(updateStrSql.ToString(), uparameters);
#endregion
} private void DelBtn_Click(object sender, RoutedEventArgs e)
{
#region 删除一条数据
StringBuilder DelStrSql = new StringBuilder();
DelStrSql.Append("delete from LoginUser ");
DelStrSql.Append(" where UserId=@ID ");
MySqlParameter[] delparameters = {
new MySqlParameter("@ID", ) };
var del = new CaseUserData().Delete(DelStrSql.ToString(), delparameters);
#endregion
} private void BatchDelBtn_Click(object sender, RoutedEventArgs e)
{
#region 批量删除数据
List<int> idLists = new List<int>();
string ids = string.Join(",", idLists); //List数组的每个元素加上引号,如("12","32","5456","876455")
string s1 = string.Format("'{0}'", ids.Replace(",", "','")); StringBuilder BatchDelStrSql = new StringBuilder();
BatchDelStrSql.Append("delete from LoginUser ");
BatchDelStrSql.Append(" where UserId in (" + s1 + ")");
var batchDel = new CaseUserData().DeleteList(BatchDelStrSql.ToString());
#endregion
} private void BatchGetListBtn_Click(object sender, RoutedEventArgs e)
{
#region 批量获取数据
StringBuilder batchGetStrSql = new StringBuilder();
batchGetStrSql.Append("select UserId,Name,Age FROM LoginUser ");
batchGetStrSql.Append(" where Age > 30");
var batchGetList = new CaseUserData().GetList(batchGetStrSql.ToString());
#endregion
} private void IsExitBtn_Click(object sender, RoutedEventArgs e)
{
#region 数据是否存在
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from LoginUser");
strSql.Append(" where UserId=@ID ");
var d = new CaseUserData().Exists(strSql.ToString(), );
#endregion
}
6、定义一些基本方法的接口:
using System;
using System.Data;
using System.Collections.Generic;
using MvvmFuncationApp.DbHelper;
using MySql.Data.MySqlClient; namespace iPIS.Server.IDAL
{
/// <summary>
/// 接口层caseuserdata
/// </summary>
public interface ICaseUserData
{
#region 成员方法
/// <summary>
/// 是否存在该记录
/// </summary>
bool Exists(string StrSql,int ID);
/// <summary>
/// 增加一条数据
/// </summary>
bool Add(string strSql,MySqlParameter[] parameters);
/// <summary>
/// 更新一条数据
/// </summary>
bool Update(string strSql, MySqlParameter[] parameters);
/// <summary>
/// 删除一条数据
/// </summary>
bool Delete(string strSql, MySqlParameter[] parameters);
bool DeleteList(string strSql);
/// <summary>
/// 得到一个对象实体
/// </summary>
ParametersModel GetModel(int ID);
/// <summary>
/// 获得数据列表
/// </summary>
List<ParametersModel> GetList(string strWhere); #endregion 成员方法
#region MethodEx #endregion MethodEx
}
}
7、定义一个类,实现方法接口:
using iPIS.Server.IDAL;
using MvvmFuncationApp.DbHelper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Runtime.Serialization;
using System.Text;
using System.Xml.Linq; namespace iPIS.Server.Core
{
/// <summary>
/// 数据访问类
/// </summary>
public partial class CaseUserData : ICaseUserData
{
public CaseUserData()
{ }
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(string StrSql,int ID)
{
MySqlParameter[] parameters = {
new MySqlParameter("@ID", MySqlDbType.Int32,) };
parameters[].Value = ID; return DbHelperMySql.Exists(StrSql.ToString(), parameters);
} /// <summary>
/// 增加一条数据
/// </summary>
public bool Add(string StrSql, MySqlParameter[] parameters)
{
int rows = DbHelperMySql.ExecuteSql(StrSql.ToString(), parameters);
if (rows > )
{
return true;
}
else
{
return false;
}
} /// <summary>
/// 更新一条数据
/// </summary>
public bool Update(string StrSql, MySqlParameter[] parameters)
{
int rows = DbHelperMySql.ExecuteSql(StrSql.ToString(), parameters);
if (rows > )
{
return true;
}
else
{
return false;
}
} /// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(string StrSql,MySqlParameter[] parameters)
{
int rows = DbHelperMySql.ExecuteSql(StrSql.ToString(), parameters);
if (rows > )
{
return true;
}
else
{
return false;
}
} /// <summary>
/// 批量删除数据
/// </summary>
public bool DeleteList(string BatchDelStrSql)
{
int rows = DbHelperMySql.ExecuteSql(BatchDelStrSql.ToString());
if (rows > )
{
return true;
}
else
{
return false;
}
} /// <summary>
/// 得到一个对象实体
/// </summary>
public ParametersModel GetModel(int ID)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select UserId,Name,Age from LoginUser ");
strSql.Append(" where UserId=@ID ");
MySqlParameter[] parameters = {
new MySqlParameter("@ID", MySqlDbType.Int32,) };
parameters[].Value = ID; ParametersModel model = new ParametersModel();
using (var ds = DbHelperMySql.ExecuteReader(strSql.ToString(), parameters))
{
while (ds.Read())
{
return DataRowToModel(ds);
}
}
return null;
} /// <summary>
/// 得到一个对象实体
/// </summary>
public ParametersModel DataRowToModel(IDataReader row)
{
ParametersModel model = new ParametersModel();
if (row != null)
{
if (row["UserId"] != null && row["UserId"].ToString() != "")
{
model.ID = int.Parse(row["UserId"].ToString());
}
if (row["Name"] != null)
{
model.Name = row["Name"].ToString();
}
if (row["Age"] != null && row["Age"].ToString() != "")
{
model.Age = int.Parse(row["Age"].ToString());
} }
return model;
} /// <summary>
/// 获得数据列表
/// </summary>
public List<ParametersModel> GetList(string strSql)
{
using (var ds = DbHelperMySql.ExecuteReader(strSql.ToString()))
{
var list = new List<ParametersModel>();
while (ds.Read())
{
list.Add(DataRowToModel(ds));
}
return list;
}
}
}
}
8、数据库操作封装类:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient; namespace MvvmFuncationApp.DbHelper
{
public abstract class DbHelperMySql
{
//数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库.
public static string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]; // "server=127.0.0.1;port=3306;database=lktest;uid=root;pwd=123456"; protected DbHelperMySql()
{
} #region 公用方法
/// <summary>
/// 得到最大值
/// </summary>
/// <param name="fieldName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public static int GetMaxId(string fieldName, string tableName)
{
string strsql = "select max(" + fieldName + ")+1 from " + tableName;
object obj = GetSingle(strsql);
return obj == null ? : int.Parse(obj.ToString());
} /// <summary>
/// 是否存在(基于MySqlParameter)
/// </summary>
/// <param name="strSql"></param>
/// <param name="cmdParms"></param>
/// <returns></returns>
public static bool Exists(string strSql, params MySqlParameter[] cmdParms)
{
var obj = GetSingle(strSql, cmdParms);
int cmdresult;
if ((Equals(obj, null)) || (Equals(obj, DBNull.Value)))
{
cmdresult = ;
}
else
{
cmdresult = int.Parse(obj.ToString());
}
return cmdresult != ;
}
#endregion #region 执行简单SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="sqlString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string sqlString)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand(sqlString, connection))
{
try
{
connection.Open();
var rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySqlException e)
{
connection.Close();
throw e;
}
}
}
} public static int ExecuteSqlByTime(string sqlString, int times)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand(sqlString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = times;
var rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySqlException e)
{
connection.Close();
throw e;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="sqlStringList">多条SQL语句</param>
public static int ExecuteSqlTran(List<String> sqlStringList)
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
var cmd = new MySqlCommand { Connection = conn };
var tx = conn.BeginTransaction();
cmd.Transaction = tx;
try
{
var count = ;
foreach (var strsql in sqlStringList.Where(strsql => strsql.Trim().Length > ))
{
cmd.CommandText = strsql;
count += cmd.ExecuteNonQuery();
}
tx.Commit();
return count;
}
catch (Exception ex)
{
tx.Rollback();
throw ex;
}
}
} /// <summary>
/// 执行带一个存储过程参数的的SQL语句。
/// </summary>
/// <param name="sqlString">SQL语句</param>
/// <param name="content">参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string sqlString, string content)
{
using (var connection = new MySqlConnection(connectionString))
{
var cmd = new MySqlCommand(sqlString, connection);
var myParameter = new MySqlParameter("@content", SqlDbType.NText) { Value = content };
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
var rows = cmd.ExecuteNonQuery();
return rows;
}
catch (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 (var connection = new MySqlConnection(connectionString))
{
var cmd = new MySqlCommand(sqlString, connection);
var myParameter = new MySqlParameter("@content", SqlDbType.NText) { Value = content };
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
var obj = cmd.ExecuteScalar();
if ((Equals(obj, null)) || (Equals(obj, DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (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 (var connection = new MySqlConnection(connectionString))
{
var cmd = new MySqlCommand(strSql, connection);
var myParameter = new MySqlParameter("@fs", SqlDbType.Image) { Value = fs };
cmd.Parameters.Add(myParameter);
try
{
connection.Open();
var rows = cmd.ExecuteNonQuery();
return rows;
}
catch (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 (var connection = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand(sqlString, connection))
{
try
{
connection.Open();
var obj = cmd.ExecuteScalar();
if ((Equals(obj, null)) || (Equals(obj, DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySqlException e)
{
connection.Close();
throw e;
}
}
}
} public static object GetSingle(string sqlString, int times)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand(sqlString, connection))
{
try
{
connection.Open();
cmd.CommandTimeout = times;
var obj = cmd.ExecuteScalar();
if ((Equals(obj, null)) || (Equals(obj, DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySqlException e)
{
connection.Close();
throw e;
}
}
}
}
/// <summary>
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="strSql">查询语句</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string strSql)
{
var connection = new MySqlConnection(connectionString);
var cmd = new MySqlCommand(strSql, connection);
try
{
connection.Open();
var myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return myReader;
}
catch (MySqlException e)
{
throw e;
} } /// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <returns>DataSet</returns>
[Obsolete("不再使用该接口,请使用ExecuteReader(string strSql)")]
public static DataSet Query(string sqlString)
{
using (var connection = new MySqlConnection(connectionString))
{
var ds = new DataSet();
try
{
connection.Open();
var command = new MySqlDataAdapter(sqlString, connection);
command.Fill(ds, "ds");
}
catch (MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
} /// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="sqlString"></param>
/// <param name="times">超时时间</param>
/// <returns></returns>
[Obsolete("不再使用该接口,请使用ExecuteReader(string strSql)")]
public static DataSet Query(string sqlString, int times)
{
using (var connection = new MySqlConnection(connectionString))
{
var ds = new DataSet();
try
{
connection.Open();
var command = new MySqlDataAdapter(sqlString, connection) { SelectCommand = { CommandTimeout = times } };
command.Fill(ds, "ds");
}
catch (MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
} /// <summary>
/// 删除案件
/// </summary>
/// <returns></returns>
public static int ExecuteProcedure(string caseid)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand())
{
try
{
cmd.Connection = connection;
connection.Open();
cmd.CommandText = "sp_DeleteCaseInfo";
cmd.CommandType = CommandType.StoredProcedure; MySqlParameter id = new MySqlParameter("?id", MySqlDbType.VarChar, );
id.Value = caseid;
cmd.Parameters.Add(id); MySqlParameter result = new MySqlParameter("?result", MySqlDbType.Int32, );
result.Direction = ParameterDirection.Output;
cmd.Parameters.Add(result); cmd.ExecuteNonQuery();
int state = int.Parse(result.Value.ToString());
return state;
}
catch (MySqlException e)
{
throw e;
}
}
}
} #endregion #region 执行带参数的SQL语句 /// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="sqlString">SQL语句</param>
/// <param name="cmdParms">参数化</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string sqlString, params MySqlParameter[] cmdParms)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, sqlString, cmdParms);
var rows = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return rows;
}
catch (MySqlException e)
{
throw e;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="sqlStringList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static void ExecuteSqlTran(Hashtable sqlStringList)
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
var cmd = new MySqlCommand();
try
{
//循环
foreach (DictionaryEntry myDe in sqlStringList)
{
var cmdText = myDe.Key.ToString();
var cmdParms = (MySqlParameter[])myDe.Value;
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
var val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
trans.Commit();
}
catch
{
trans.Rollback();
throw;
}
}
}
} /// <summary>
/// 执行多条SQL语句,实现数据库事务。
/// </summary>
/// <param name="cmdList">SQL语句的哈希表(key为sql语句,value是该语句的MySqlParameter[])</param>
public static int ExecuteSqlTran(List<CommandInfo> cmdList)
{
using (var conn = new MySqlConnection(connectionString))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
var cmd = new MySqlCommand();
try
{
var count = ;
//循环
foreach (var myDe in cmdList)
{
string cmdText = myDe.CommandText;
var 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(") == -)
{
trans.Rollback();
return ;
} object obj = cmd.ExecuteScalar();
bool isHave = false;
if (obj == null && obj == DBNull.Value)
{
isHave = false;
}
isHave = Convert.ToInt32(obj) > ; if (myDe.EffentNextType == EffentNextType.WhenHaveContine && !isHave)
{
trans.Rollback();
return ;
}
if (myDe.EffentNextType == EffentNextType.WhenNoHaveContine && isHave)
{
trans.Rollback();
return ;
}
continue;
}
int val = cmd.ExecuteNonQuery();
count += val;
if (myDe.EffentNextType == EffentNextType.ExcuteEffectRows && val == )
{
trans.Rollback();
return ;
}
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 (var conn = new MySqlConnection(connectionString))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
var cmd = new MySqlCommand();
try
{
var indentity = ;
//循环
foreach (var myDe in sqlStringList)
{
var cmdText = myDe.CommandText;
var cmdParms = (MySqlParameter[])myDe.Parameters;
foreach (var q in cmdParms)
{
if (q.Direction == ParameterDirection.InputOutput)
{
q.Value = indentity;
}
}
PrepareCommand(cmd, conn, trans, cmdText, cmdParms);
int val = cmd.ExecuteNonQuery();
foreach (var 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 (var conn = new MySqlConnection(connectionString))
{
conn.Open();
using (var trans = conn.BeginTransaction())
{
var cmd = new MySqlCommand();
try
{
var indentity = ;
//循环
foreach (DictionaryEntry myDe in sqlStringList)
{
string cmdText = myDe.Key.ToString();
var 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>
/// <param name="cmdParms">参数化</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string sqlString, params MySqlParameter[] cmdParms)
{
using (var connection = new MySqlConnection(connectionString))
{
using (var cmd = new MySqlCommand())
{
try
{
PrepareCommand(cmd, connection, null, sqlString, cmdParms);
var obj = cmd.ExecuteScalar();
cmd.Parameters.Clear();
if ((Equals(obj, null)) || (Equals(obj, DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (MySqlException e)
{
throw e;
}
}
}
} /// <summary>
/// 执行查询语句,返回MySqlDataReader ( 注意:调用该方法后,一定要对MySqlDataReader进行Close )
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <param name="cmdParms">参数化</param>
/// <returns>MySqlDataReader</returns>
public static MySqlDataReader ExecuteReader(string sqlString, params MySqlParameter[] cmdParms)
{
var connection = new MySqlConnection(connectionString);
var cmd = new MySqlCommand();
try
{
PrepareCommand(cmd, connection, null, sqlString, cmdParms);
var myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return myReader;
}
catch (MySqlException e)
{
throw e;
}
// finally
// {
// cmd.Dispose();
// connection.Close();
// } } /// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <param name="cmdParms">参数化</param>
/// <returns>DataSet</returns>
[Obsolete("不再使用该接口,请使用ExecuteReader(string sqlString, params MySqlParameter[] cmdParms)")]
public static DataSet Query(string sqlString, params MySqlParameter[] cmdParms)
{
using (var connection = new MySqlConnection(connectionString))
{
var cmd = new MySqlCommand();
PrepareCommand(cmd, connection, null, sqlString, cmdParms);
using (var da = new MySqlDataAdapter(cmd))
{
var ds = new DataSet();
try
{
da.Fill(ds, "ds");
cmd.Parameters.Clear();
}
catch (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
}
}
9、数据库数据转模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace MvvmFuncationApp.DbHelper
{
/// <summary>
/// 案件关联用户自定义数据
/// </summary>
[Serializable]
public partial class ParametersModel
{
public ParametersModel()
{ }
#region Model
private int _id;
private string _DataID;
private int _age;
private string _name;
private string _userdata;
private string _extended1;
private string _extended2;
/// <summary>
///
/// </summary>
public int ID
{
set { _id = value; }
get { return _id; }
}
/// <summary>
/// 关联数据ID,DataType=1 案件id;DataType=2 图片id
/// </summary>
public string DataID
{
set { _DataID = value; }
get { return _DataID; }
}
/// <summary>
/// 数据类型。详见枚举值
/// </summary>
public int Age
{
set { _age = value; }
get { return _age; }
}
/// <summary>
/// 数据名称
/// </summary>
public string Name
{
set { _name = value; }
get { return _name; }
}
/// <summary>
/// 数据详细内容
/// </summary>
public string UserData
{
set { _userdata = value; }
get { return _userdata; }
}
/// <summary>
///
/// </summary>
public string Extended1
{
set { _extended1 = value; }
get { return _extended1; }
}
/// <summary>
///
/// </summary>
public string Extended2
{
set { _extended2 = value; }
get { return _extended2; }
}
#endregion Model } }
可以直接使用,亲测没问题。
VisualStudio 连接 MySql 实现增删查改的更多相关文章
- Python对MySQL进行增删查改
python连接MySQL数据库:pymysql # 测试操作 import pymysql # 打开数据库 db = pymysql.connect("localhost", & ...
- Nhibernate入门篇连接Sqlserver的增删查改
第一步:创建数据库 create table Emp( EmpId int primary key identity, EmpName ), EmpDate date ) 第二步:去官网下载:http ...
- Mysql常用增删查改及入门(二)
常用:数据库常用就是DML:增删查改 1.增加数据: insert into 表名 values (值1,值2...); insert into 表名 (字段1,字段2) values (值1,值2) ...
- 后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)
1 前言&概述 这篇文章是基于这篇文章的更新,主要是更新了一些技术栈以及开发工具的版本,还有修复了一些Bug. 本文是SpringBoot+Android+MySQL的增删查改的简单实现,用到 ...
- nodejs连接mysql并进行简单的增删查改
最近在入门nodejs,正好学习到了如何使用nodejs进行数据库的连接,觉得比较重要,便写一下随笔,简单地记录一下 使用在安装好node之后,我们可以使用npm命令,在项目的根目录,安装nodejs ...
- Java连接MySQL数据库及简单的增删查改操作
主要摘自 https://www.cnblogs.com/town123/p/8336244.html https://www.runoob.com/java/java-mysql-connect.h ...
- node.js+mysql增删查改
数据库和表: -- -- 数据库: `test` -- -- -------------------------------------------------------- -- -- 表的结构 ` ...
- php mysql增删查改
php mysql增删查改代码段 $conn=mysql_connect('localhost','root','root'); //连接数据库代码 mysql_query("set na ...
- PHP与MYSQL结合操作——文章发布系统小项目(实现基本增删查改操作)
php和mysql在一起几十年了,也是一对老夫老妻了,最近正在对他们的爱情故事进行探讨,并做了一个很简单的小东西——文章发布系统,目的是为了实现mysql对文章的基本增删查改操作 前台展示系统有:文章 ...
随机推荐
- 排序---希尔排序Java
希尔排序 插入排序的一种又称“缩小增量排序”,是直接插入排序算法的一种更高效的改进版本.希尔排序是非稳定排序算法. 希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序:随着增量逐渐减 ...
- 如何在 Debian 9 上安装和使用 Docker
Docker 是一个容器化平台,允许您快速构建,测试和部署应用程序,作为便携式,自给自足的容器,几乎可以在任何地方运行. Docker 是容器技术的事实上的标准,它是 DevOps 工程师及其持续集成 ...
- 微信小程序之页面传参
效果图: 点击编辑值传过去了,那么编辑支出类型这个界面又是如何获取到值呢? 传值代码: type.js editType: function (e) { var typeId = e.currentT ...
- 用DLL方式封装MDI子窗体
用DLL方式封装MDI子窗体是一种常用的软件研发技术,他的长处: 研发人员能够负责某一个模块的编写包括(界面+逻辑),能够互不干扰,模块研发完成后,主程式统一调用. 易于程式升级,当程式升级时,不用编 ...
- 系统树图 | Dendrogram construction | Phylogenetic Analysis
Molecular Architecture of the Mouse Nervous System 表示亲缘关系的树状图解 先看文章里是怎么做的: Dendrogram construction A ...
- 自动化远程部署shell脚本
历史原因,有一段时间,项目开发采用一种模式:项目开发及代码版本管理在外网,而主要测试在内网.所以为了同步开发进度,每天会将所有服务在外网jenkins上打包好,然后将服务jar包拷进内网,由于内网服务 ...
- Comparator中返回0导致数据丢失的大坑
今天对一列数据进行排序,因为存储的是Map结构,要实现排序,马上就想到了TreeMap,于是查到API,这样新建TreeMap就能实现添加的时候就自动排序. new TreeMap<>(n ...
- ISO/IEC 9899:2011 引言
引言 1.伴随着新的设备以及扩展字符集的引入,可能会将新的特性添加到此国际标准中.在此语言和库条款中的子条款提醒了实现者与程序员可能会与将来所新增特性产生冲突的用法,尽管它们现在本身是合法有效的. 2 ...
- Python3基础 函数 函数名作为参数传给函数
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- WebAPI.请求(Request)的参数(Parameter)里包含特殊字符(#等)的正确处理方式 从客户端xx中检测到有潜在危险的Request.Form值
事故现场 报错"从客户端 中检测到有潜在危险的Request.Form值" //后台代码 namespace Test { [RoutePrefix("TestClass ...