连接到MySQL数据库,这里连接的是已经准备好的本地的数据库student:
//获取连接字符串
static public string GetConnectStr()
{
var build = new MySqlConnectionStringBuilder() {
Server = "localhost",
UserID = "root",
Password = "123456",
Database = "student" };
return build.ConnectionString;
}
//获取数据库连接对象
static public SqlSugarClient GetConnectionObj()
{
// 创建数据库连接对象
var db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = GetConnectStr(), // 连接字符串
DbType = DbType.MySql, // 数据库类型
IsAutoCloseConnection = true, // 自动关闭连接
InitKeyType = InitKeyType.Attribute // 初始化主键和自增列信息
});
return db;
}
准备与数据库对应的实体表格:
实体与数据库结构一样
//public class Student
//{
// //数据是自增需要加上IsIdentity
// //数据库是主键需要加上IsPrimaryKey
// //注意:要完全和数据库一致2个属性
// [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
// public int Id { get; set; }
// public int? SchoolId { get; set; }
// public string Name { get; set; }
//}
//可通过添加特性与数据库表对应,此时实体可与表名不相同
//[SugarTable("Student")]
internal class bsae_info
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
}
简单的sqlsugar语句的使用:
static void Main(string[] args)
{
//string connectionString = "Server=localhost;Database=student;Uid=root;Pwd=123456;Charset=utf8;";
// 创建数据库连接对象
SqlSugarClient db = GetConnectionObj();
// 创建待插入数据
var data = new bsae_info() { id = 2 ,name = "Sandy" , age = 13};
// 插入数据
db.Insertable(data).ExecuteCommand();
// 执行插入操作
db.Ado.ExecuteCommand("INSERT INTO bsae_info (id, name, age) VALUES (@id,@name,@age)",
new {id = data.id, name = data.name, age=data.age });
//int count = db.Queryable<Student>().Count();
//Console.WriteLine(count);
//查询所有数据
var list = Db.Queryable<Student>().ToList();
//带条件查询
var list = db.Queryable<bsae_info>().Where(it => it.id == 3).ToList();
//打印查询结果
foreach (bsae_info student in list)
{
Console.WriteLine(student.name);
}
}