搞了几年Java,现在转过头来再用C sharp写东西,感觉有种沧海桑田的感觉。呵呵。。。
//pay attention:在DAL中,使用MySqlDBFactory获取连接
#region 插入数据--单条,批量
using (var conn = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;database=chargerecord;uid=root;pwd=root;charset=utf8;"))
{
IDbTransaction trans = conn.BeginTransaction();//需要手动开启事务控制
var r = conn.Execute(@"insert users(Id, UserName,PassWord) values (@Id, @UserName,@PassWord)",
new[] {
new { Id = 1, UserName = "lhc1",PassWord="123"}
, new { Id = 2, UserName = "lhc2",PassWord="123"}
, new { Id = 3, UserName = "lhc3",PassWord="123"}
});
trans.Commit();
}
#endregion
#region 查询全部数据并返回集合
List<TestUsers> userList;
using (var conn = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;database=chargerecord;uid=root;pwd=root;charset=utf8;"))
{
userList = conn.Query<TestUsers>("select * from users").AsList();
Console.WriteLine(userList);
}
#endregion
#region 按照条件查询
using (var conn = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;database=chargerecord;uid=root;pwd=root;charset=utf8;"))
{
var result = conn.Query<TestUsers>("select * from users where id=@Id", new { Id = 1 }).FirstOrDefault();
Console.WriteLine(result.Id);
Console.ReadKey();
}
#endregion
#region 登陆查询
UserInfoEntity user = new UserInfoEntity();
using (var conn = new MySqlConnection("server=localhost;database=chargerecord;uid=root;pwd=root;charset=utf8;"))
{
user = conn.Query<UserInfoEntity>("SELECT tempuser.UserName,tempuser.`PassWord`,tempuser.RepositoryId,repo.RepositoryName FROM `users` tempuser LEFT JOIN repository repo on tempuser.RepositoryId = repo.id where tempuser.UserName=@userName and tempuser.PassWord=@passWord", new { userName = "lhc", passWord = "123" }).FirstOrDefault();
}
Console.ReadKey();
#endregion