.Net dapper访问数据库

414 阅读1分钟
  • 1:添加daper NuGet管理包;
  • 2: using Dapper; using System.Data; using System.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
using System.Data.SqlClient;
namespace dapperDemo
{
    public static class DBHelpers
    {
        private static string conStr = "Data Source=.;Initial Catalog=Bw;Integrated Security=True";
        public static int Execute()
        {
            using (IDbConnection connection = new SqlConnection(conStr))
            {
                Book book = new Book();
                book.Name = "123";
                //return connection.Execute($"insert into Book values(@Name)", book);
                //return connection.Execute($"insert into Book values(@Name)",new { Name="456"});
                //return connection.Execute($"delete from Book where Id =@Id", new { Id = 5 });
                return connection.Execute($"update Book set Name=@Name where Id =@Id", new { Id = 6,Name="111" }); 
            }
        }
        public static List<T> Get<T>()
        {
            using (IDbConnection connection = new SqlConnection(conStr))
            {
                //return (List<T>)connection.Query<T>($"select * from book");
                return (List<T>)connection.Query<T>($"select * from book where Name=@Name",new { Name="111"});
            }
        }
    }
    public class Book
    {
        public string Name { get; set; }
    }
}