Dapper操作Sql Server和MySql數據庫


1. 在配置文件web.config中添加連接字符串

<connectionStrings>
  <add name="sqlconnectionString" connectionString="server=127.0.0.1;database=MyDataBase;User=sa;password=123456;Connect Timeout=1000000"/>
  <add name="mysqlconnectionString" connectionString="Data Source=127.0.0.1;Database=hyd;User Id=root;Password=root;CharSet=utf8;port=3306"/> 
</connectionStrings>

2. 獲取連接數據庫對象

 獲取Sql Server的連接數據庫對象SqlConnection  

public static SqlConnection SqlConnection()
{
      string sqlconnectionString = ConfigurationManager.ConnectionStrings["sqlconnectionString"].ToString();
      var connection = new SqlConnection(sqlconnectionString);
      connection.Open();
      return connection;
}

獲取MySql的連接數據庫對象 MySqlConnection  

public static MySqlConnection MySqlConnection()
{
       string mysqlconnectionString = ConfigurationManager.ConnectionStrings["mysqlconnectionString"].ToString();
       var connection = new MySqlConnection(mysqlconnectionString);
       connection.Open();
       return connection;
}

3. 實體類

public class Users
{
     public int ID { get; set; }//自增主鍵
     public string Name { get; set; }
     public int  Age { get; set; }
}

4. 增刪改查

    //
    using (IDbConnection conn = DapperService.MySqlConnection())
    {
        Users user = new Users();
        user.Name = "CNKI";
        user.Age = 38;
        string sqlCommandText = @"INSERT INTO USERS(Name,Age)VALUES(@Name,@Age)";
        int result = conn.Execute(sqlCommandText, user);
    }
    //批量增
    using (IDbConnection conn = DapperService.MySqlConnection())
    {
        List<Users> list = new List<Users>();
        for (int i = 0; i < 5; i++)
        {
            Users user = new Users();
            user.Name = "CNKI";
            user.Age = 38;
            list.Add(user);
        }
        string sqlCommandText = @"INSERT INTO USERS(Name,Age)VALUES(@Name,@Age)";
        int result = conn.Execute(sqlCommandText, list);
    }
    //
    using (IDbConnection conn = DapperService.MySqlConnection())
    {
        Users user = new Users();
        user.ID = 1;
        string sqlCommandText = @"DELETE FROM USERS WHERE ID=@ID";
        int result = conn.Execute(sqlCommandText, user);
    }
    //
    using (IDbConnection conn = DapperService.MySqlConnection())
    {
        Users user = new Users();
        user.ID = 2;
        user.Name = "CNKI";
        user.Age = 18;
        string sqlCommandText = @"UPDATE USERS SET Age=@Age WHERE ID=@ID";
        int result = conn.Execute(sqlCommandText, user);
    }
    //
    using (IDbConnection conn = DapperService.MySqlConnection())
    {
        string sqlCommandText = @"SELECT * FROM USERS WHERE ID=@ID";
        Users user = conn.Query<Users>(sqlCommandText, new  { ID=2 }).FirstOrDefault();
    }
    //分頁
    using (IDbConnection conn = DapperService.MySqlConnection())
    {
        int pageIndex = 0;
        int pageSize = 2;
        string sqlCommandText = string.Format(@"SELECT * FROM USERS  LIMIT {0},{1} ", pageIndex * pageSize, pageSize);
        List<Users> user = conn.Query<Users>(sqlCommandText).ToList();
    }

5. 防止Sql注入

using (IDbConnection conn = DapperService.MySqlConnection())
{
     string sqlCommandText = @"SELECT * FROM USER WHERE ID=@ID";
     var p = new DynamicParameters();
     p.Add("@ID", 1);
     User user = conn.Query<User>(sqlCommandText,p).FirstOrDefault();
}

這里用到了Dapper的DynamicParameters動態參數集合類,從上面可以看到可以能過Add方法加入參數。最后通過conn.Query<MSys_Admin>(sqlText, p)執行sql,,返回結果。因為用的是命令參數的形式,讓sql注入無機可乘,所以這種方案是安全的。

6. 操作事物

 public void TestDapperTransaction()
 {
       using (var conn = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;Database=test;User Id=root;password=root"))
       {
           conn.Open();
           //開戶事務
           IDbTransaction trans = conn.BeginTransaction();
           try
           {
               int row = conn.Execute(@"update t set name='www.lanhusoft.com' where id=@id", new { id = 3 }, trans);
               row += conn.Execute("delete from t where id=@id", new { id = 5 }, trans);
               for (int i = 0; i < 100; i++)
               {
                    conn.Execute(@"insert t(id, name) values (@id, @name)", new { id = i, name = "www.lanhusoft.com/" + i });
               }
               trans.Commit(); //提交事務
               conn.Close();
           }
           catch (Exception)
           {
               trans.Rollback(); //回滾事務
               conn.Close();
           }
      }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM