C#访问MySQL(二):数据插入与修改(增改)
前言:
前面说了数据库的连接查询,现在说数据库的增删改。这里引入一个数据库的实体类,就是将当前数据库的某一个表里面所有字段写成实体类,如下:
1.数据库的实体类:
需要项目里下载Chloe.dll和Chloe.Mysql.dll,如下:
例如有表如下:
它的实体类就是:
using System;
using Chloe.Entity;
using Chloe.Annotations;
namespace WpfApp1
{
/// <summary>
/// 实体类tb_a。(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("tb_a")]
[Serializable]
public partial class Tb_A
{
#region Model
private int _ID;
private string _Name;
private int? _Age;
private int? _Sex;
/// <summary>
/// ID
/// </summary>
[ColumnAttribute(IsPrimaryKey = true)]
public int ID
{
get { return _ID; }
set
{
this._ID = value;
}
}
/// <summary>
/// 名字
/// </summary>
public string Name
{
get { return _Name; }
set
{
this._Name = value;
}
}
/// <summary>
/// 年龄
/// </summary>
public int? Age
{
get { return _Age; }
set
{
this._Age = value;
}
}
/// <summary>
/// 性别
/// </summary>
public int? Sex
{
get { return _Sex; }
set
{
this._Sex = value;
}
}
#endregion
}
}
2.增加一行数据:
封装一下IDbConnectionFactory。
public class MySqlConnectionFactory : IDbConnectionFactory
{
string _connString = null;
public MySqlConnectionFactory(string connString)
{
this._connString = connString;
}
public IDbConnection CreateConnection()
{
IDbConnection conn = new MySqlConnection(this._connString);
return conn;
}
}
插入一行数据方法:
internal static bool InsertNewData(Tb_A Model, out long lID)
{
MySqlContext context = new MySqlContext(new MySqlConnectionFactory("host = 数据库IP; Port = 数据库端口; Database = 数据库名; uid = 数据库账户; pwd = 数据库密码; Charset = utf8; Allow User Variables = true"));
using (MySqlContext dx = context)
{
IQuery<Tb_A> q = dx.Query<Tb_A>();
lID = dx.Insert<Tb_A>(Model).ID;
return true;
}
}
调用:
private void Button_Click(object sender, RoutedEventArgs e)
{
Tb_A Model = new Tb_A()
{
Age = 18,
Name = "张三",
Sex = 1,
};
long ID = 0;
InsertNewData(Model,out ID);
}
结果:
3.修改某一行数据:
方法:
internal static bool UpdateName(string name,long ID)
{
try
{
MySqlContext context = new MySqlContext(new MySqlConnectionFactory("host = 数据库IP; Port = 数据库端口; Database = 数据库名; uid = 数据库账户; pwd = 数据库密码; Charset = utf8; Allow User Variables = true"));
using (MySqlContext dx = context)
{
return dx.Update<Tb_A>(a => a.ID == ID, a => new Tb_A()
{
Name = name,
}) >= 0;
}
}
catch (Exception)
{
return false;
}
}
调用:
private void Button_Click(object sender, RoutedEventArgs e)
{
Tb_A Model = new Tb_A()
{
Age = 18,
Name = "张三",
Sex = 1,
};
long ID = 1;
UpdateName("李四" , ID);
}
结果: