利用C#直接连接MySql
这里注意看清是那个NetFrame版本的,项目和文件要对应。
2.引用Mysql.Data.MySqlClient,实现数据库连接
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace CSharp连接数据库
{
class Program
{
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=123456;";
MySqlConnection conn = new MySqlConnection(connectStr);//并没有和数据库建立连接
try
{
conn.Open();
Console.WriteLine("已经建立连接");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
conn.Close();
}
Console.ReadKey();
}
}
}
3.使用c#做查询全部数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace CSharp连接数据库
{
class Program
{
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=123456;";
MySqlConnection conn = new MySqlConnection(connectStr);//并没有和数据库建立连接
try
{
conn.Open();
string sql = "select * from users";
MySqlCommand cmd = new MySqlCommand(sql,conn);
Console.WriteLine("已经建立连接");
//cmd.ExecuteReader();//执行一些查询,得到全部数据
//cmd.ExecuteNonQuery();//插入 删除
//cmd.ExecuteScalar();//执行一些查询,并且返回一个单个的值
MySqlDataReader reader=cmd.ExecuteReader();
while(reader.Read()) { //读取下一页数据,如果读取成功,返回true,如果没有下一页了,读取失败的话,返回false
Console.WriteLine(reader[0].ToString()+ reader[1].ToString() + reader[2].ToString());
Console.WriteLine(reader.GetInt32("id")+" "+reader.GetString("username") +" "+reader.GetString("password"));
Console.WriteLine(reader.GetInt32(0)+" "+reader.GetString(1) +" "+reader.GetString(2));
//三种得到行的方法
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
conn.Close();
}
Console.ReadKey();
}
}
}
4.使用c#进行插入操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace CSharp连接数据库
{
class Program
{
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=123456;";
MySqlConnection conn = new MySqlConnection(connectStr);//并没有和数据库建立连接
try
{
conn.Open();
string sql = "insert into users(username,password,registerdate) values('asddasdsa','123','"+DateTime.Now+"')";
MySqlCommand cmd = new MySqlCommand(sql,conn);
Console.WriteLine("已经建立连接");
//cmd.ExecuteNonQuery();//插入 删除
int result = cmd.ExecuteNonQuery();//返回值是数据库中受影响的行数
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
conn.Close();
}
Console.ReadKey();
}
}
}
5.修改,删除操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace CSharp连接数据库
{
class Program
{
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=123456;";
MySqlConnection conn = new MySqlConnection(connectStr);//并没有和数据库建立连接
try
{
conn.Open();
string sql = "update users set username='asdsad',password='45464' where id=4";
//删除
//string sql = "delete from users where id=4";
MySqlCommand cmd = new MySqlCommand(sql,conn);
Console.WriteLine("已经建立连接");
//cmd.ExecuteNonQuery();//插入 删除 修改
int result = cmd.ExecuteNonQuery();//返回值是数据库中受影响的行数
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
conn.Close();
}
Console.ReadKey();
6.sql函数,使用ExecuteScalar()输出函数结果
http://www.w3school.com.cn/sql/index.asp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace CSharp连接数据库
{
class Program
{
static void Main(string[] args)
{
string connectStr = "server=127.0.0.1;port=3306;database=mygamedb;user=root;password=123456;";
MySqlConnection conn = new MySqlConnection(connectStr);//并没有和数据库建立连接
try
{
conn.Open();
Console.WriteLine("已经建立连接");
string sql = "select count(*) from users";
MySqlCommand cmd = new MySqlCommand(sql,conn);
object o=cmd.ExecuteScalar();
int count = Convert.ToInt32(o);
Console.WriteLine(count);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
conn.Close();
}
Console.ReadKey();
}
}
}
7.小例子 检查用户名和密码
static bool VerifyUser(string username,string password)
{
string connectStr="server = 127.0.0.1; port = 3306; database = mygamedb; user = root; password = 123456; ";
MySqlConnection conn = new MySqlConnection(connectStr);//并没有和数据库建立连接
try
{
conn.Open();
Console.WriteLine("已经建立连接");
string sql = "select * from users where username=@username and password=@password";
// string sql = "select * from users where username="+username+" and password="+password;
MySqlCommand cmd = new MySqlCommand(sql,conn);
//增加@时候要写
cmd.Parameters.AddWithValue("username",username);
cmd.Parameters.AddWithValue("password",password);
MySqlDataReader reader=cmd.ExecuteReader();
if (reader.Read())
{
conn.Close();
return true;
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
conn.Close();
}
return false;
}
}
}
利用nhibernate连接MySql
1.利用NuGet下载MySql.Date和nhibernate
2.表的映射和对数据库的映射
(1)创建hibernate.cfg.xml在跟目录
配置内容:
NHibernate.Connection.DriverConnectionProvider
NHibernate.Dialect.MySQL5Dialect
NHibernate.Driver.MySqlDataDriver
Server=localhost;Database=mygamedb;User ID=root;Password=123456
true
(2)再建两个文件夹和各自的两个类,类名和表名一样
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wangyihui.Model
{
public class User
{
public virtual int Id { get; set; }
public virtual string Username { get; set; }
public virtual string Password { get; set; }
public virtual DateTime Registerdate { get; set; }
}
}
在User.hbm.xml的属性修改
(4)在主程序里配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Cfg;
namespace Wangyihui
{
class Program
{
static void Main(string[] args)
{
var configuration = new Configuration();
configuration.Configure();//解析hibernate.cfg.xml
configuration.AddAssembly("Wangyihui");//解析映射文件 User.hbm.xml .....
Console.ReadKey();
}
}
}
3
对数据库进行添加操作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Cfg;
using Wangyihui.Model;
namespace Wangyihui
{
class Program
{
static void Main(string[] args)
{
var configuration = new Configuration();
configuration.Configure();//解析hibernate.cfg.xml
configuration.AddAssembly("Wangyihui");//解析映射文件 User.hbm.xml .....
Console.WriteLine("成功");
ISessionFactory sessionFactory = null;
ISession session = null;
try
{
sessionFactory = configuration.BuildSessionFactory();
session = sessionFactory.OpenSession();//打开一个跟数据库的会话
User user = new User() { Username = "asdadssada111111", Password = "213132" };
session.Save(user);
Console.Write("成功");
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (session != null)
{
session.Close();
}
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
Console.ReadKey();
}
}
}
4.事务 :对于事物内的对数据库的操作,如果其中有一个操作失败了,则事务内的所有操作都会回滚,例子是支付宝取钱
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Cfg;
using Wangyihui.Model;
namespace Wangyihui
{
class Program
{
static void Main(string[] args)
{
var configuration = new Configuration();
configuration.Configure();//解析hibernate.cfg.xml
configuration.AddAssembly("Wangyihui");//解析映射文件 User.hbm.xml .....
Console.WriteLine("成功");
ISessionFactory sessionFactory = null;
ISession session = null;
ITransaction transaction = null;
try
{
sessionFactory = configuration.BuildSessionFactory();
session = sessionFactory.OpenSession();//打开一个跟数据库的会话
transaction = session.BeginTransaction();//开启事务
User user = new User() { Username = "asdadssada111111", Password = "213132" };
session.Save(user);
User user1 = new User() { Username = "asdadssada111111", Password = "213132" };
session.Save(user);
transaction.Commit();//关闭事务
Console.Write("成功");
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (transaction!=null)
{
transaction.Dispose();
}
if (session != null)
{
session.Close();
}
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
Console.ReadKey();
}
}
}
5.单独一个hibernate类,不用写多余的代码,建一个管理类用来管理Nhibernate定义出来的表对象
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NHibernate;
using NHibernate.Cfg;
namespace Wangyihui
{
class NHibernateHelper
{
private static ISessionFactory sessionFactory = null;
private static ISessionFactory SessionFactory
{
get
{
if(sessionFactory==null)
{
var configuration = new Configuration();
configuration.Configure();//解析hibernate.cfg.xml
configuration.AddAssembly("Wangyihui");//解析映射文件 User.hbm.xml .....
}
return sessionFactory;
}
}
public static ISession OpenISession()
{
return sessionFactory.OpenSession();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wangyihui.Model;
namespace Wangyihui.Manager
{
interface InterfaceTable
{
void Add(T t);
void Remove(Int32 id);
void Remove(T t);
void Update(T t);
T GetById(Int32 id);
T GetByUsername(string username);
ICollection GetAll();
bool EqXAndY(string X,string Y);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wangyihui.Model;
using NHibernate;
using NHibernate.Criterion;
namespace Wangyihui.Manager
{
class UserTableManager : InterfaceTable
{
public void Add(User user)
{
using(ISession session = NHibernateHelper.OpenISession())//使用using,使用完后会对里面的对象进行释放
{
session.Save(user);
Console.WriteLine("成功了");
}
}
public bool EqXAndY(string X, string Y)
{
using (ISession session = NHibernateHelper.OpenISession())
{
User user=session.CreateCriteria(typeof(User)).
Add(Restrictions.Eq("Username", X)).
Add(Restrictions.Eq("Password", Y)).
UniqueResult();
if (user == null) return false;
return true;
}
}
public ICollection GetAll()
{
using (ISession session =NHibernateHelper.OpenISession())
{
return session.CreateCriteria(typeof(User)).List();
}
}
public User GetById(Int32 id)
{
using (ISession session = NHibernateHelper.OpenISession())//使用using,使用完后会对里面的对象进行释放
{
return session.Get(id);
}
}
public User GetByUsername(String username)
{
using (ISession session = NHibernateHelper.OpenISession())//使用using,使用完后会对里面的对象进行释放
{
//使用了CreateCriteria进行复杂查询
return session.CreateCriteria(typeof(User)).Add(Restrictions.Eq("Username",username)).UniqueResult();
}
}
public void Remove(Int32 id)
{
using (ISession session = NHibernateHelper.OpenISession())//使用using,使用完后会对里面的对象进行释放
{
using (ITransaction transaction = session.BeginTransaction()) {
User user = GetById(id);
if (user!=null)
{
session.Delete(user);
Console.WriteLine("成功了");
transaction.Commit();
}
else
{
Console.WriteLine("没有找到");
}
}
}
}
public void Remove(User user)
{
using (ISession session = NHibernateHelper.OpenISession())//使用using,使用完后会对里面的对象进行释放
{
using (ITransaction transaction = session.BeginTransaction())
{
if (user.Id!=0)
{
User user1 = GetById(user.Id);
if (user != null)
{
session.Delete(user1);
Console.WriteLine("成功了");
transaction.Commit();
}
else
{
Console.WriteLine("没有找到");
}
}
else
{
Console.WriteLine("请输入id");
}
}
}
}
public void Update(User user)
{
using (ISession session = NHibernateHelper.OpenISession())//使用using,使用完后会对里面的对象进行释放
{
using (ITransaction transaction = session.BeginTransaction())
{
User user1 = GetById(user.Id);
if (user1!= null)
{
user1.Username = user.Username;
user1.Password = user.Password;
user1.Registerdate = user.Registerdate;
session.Update(user1);
Console.WriteLine("成功了");
transaction.Commit();
}
else
{
Console.WriteLine("没有找到");
}
}
}
}
}
}