IDbConnection connection = new SqlConnection("URI=file:./MyData.db");
// 插入,当然也可以将user类单独拿出来,做成模型 var result = connection.Execute("INSERT INTO users VALUES (@id, @name,@password)", new { id = 1, name = "jack", password = "123456"});
// 批量插入 var result = connection.Execute("insert into UserInfo(Address,Name) values(@address,@name)", new[] { new { Address = "上海", Name = "李四" }, new { Address = "北京", Name = "王五" }, new { Address = "杭州", Name = "赵六" } });
// 查询一个 User testUser = connection.Query<User>("SELECT id, name FORM users WHERE name = @name", new {name = "test"}).FirstOrDefault();
// 查询多个 IEnumerable<User> targetUsers = connection.Query<User>("SELECT id, name FORM users WHERE name like \"%@param%\"", new {param = "test"});
// 更新 connection.Execute("UPDATE users SET name=@name where id=@id", new {id=12, name="test"});
// 删除 connection.Execute("DELETE FROM users WHERE name = @name", new {name="test"});
// in写法 conn.Query<Users>("SELECT * FROM Users s WHERE s.id IN (@ids) ",new { ids = newint[]{1,2,3}})
// 多结果查询 multi = connection.QueryMultiple("SELECT * FROM books; SELECT * FROM users"); IEnumerable<Book> books = multi.Read<Book>(); IEnumerable<User> users = multi.Read<User>();
// 表关联查询 publicclassBookWithPerson { publicint ID { get; set; } public Person Pers { get; set; } publicstring BookName { get; set; } }
publicstatic BookWithPerson QueryJoin(Book book) { using (IDbConnection connection = new SqlConnection(connectionString)) { var sql = @"select b.id,b.bookName,p.id,p.name,p.remark from Person as p join Book as b on p.id = b.personId where b.id = @id;"; var result = connection.Query<BookWithPerson, Person, BookWithPerson> // 委托类型1,委托类型2,返回值类型 (sql,(bookWithPerson, person) => { bookWithPerson.Pers = person; return bookWithPerson; }, book);
return (BookWithPerson)result; } }
目前了解的函数有
Query 一般的查询
Execute 一般的执行
QueryMultiple 多语句查询
QueryFirst 查询第一个,如果没有会报错
QueryFirstOrDefault 查询第一个,为空不报错并返回null
QuerySingle 查询一个,与First不同的是,如果得到多个会报错,同时查出为空也报错
QuerySingleOrDefault 查询一个,为空不报错并返回null
包装使用
显然处处使用
1 2 3 4 5 6
using (IDbConnection connection = new SqlConnection(connectionString)) { var sql = "SELECT * FROM users where id=@id"; User result = connection.Query<User>(sql, new {id = 123}); return result; }