首页 > 代码库 > 二、Dapper,向数据库中增加数据

二、Dapper,向数据库中增加数据

一、先创建一张“学生”表(注,本文用的数据库是Mysql)

CREATE TABLE `t_student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(6) NOT NULL DEFAULT ‘‘ COMMENT ‘姓名‘,
  `sex` bit(1) NOT NULL DEFAULT b‘0‘ COMMENT ‘性别,0表示女,1表示男‘,
  `age` tinyint(3) NOT NULL DEFAULT ‘0‘ COMMENT ‘年龄‘,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=‘学生‘;

 

二、先写一个“”类,里面实现数据库连接相关

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//
using MySql.Data.MySqlClient;
using System.Data;

namespace Dapper_demo
{
    /// <summary>
    /// 连接类
    /// </summary>
    public class Dbhelper
    {
        /// <summary>
        /// Mysql连接字符串
        /// </summary>
        public static string MysqlConnectionString = "server=localhost;user id=root;password=root;database=dapper;port=3306;character set=utf8";

        private static IDbConnection connection;
        /// <summary>
        /// 获取db连接
        /// </summary>
        /// <returns></returns>
        public static IDbConnection GetConnection()
        {
            IDbConnection myConn = new MySqlConnection(MysqlConnectionString);
            string connectionString = myConn.ConnectionString;
            if (connection == null)
            {
                connection = new MySqlConnection(connectionString);
                connection.Open();
            }
            else if (connection.State == System.Data.ConnectionState.Closed)
            {
                connection.Open();
            }
            else if (connection.State == System.Data.ConnectionState.Broken)
            {
                connection.Close();
                connection.Open();
            }
            return connection;
        }
    }
}

 

三、插入单条数据

            using (var conn = Dbhelper.GetConnection())
            {
                int res = conn.Execute("insert into t_student(`name`,`sex`,`age`) values(@name,@sex,@age)", new { name = "张三", sex = 1, age = 23 });
                Console.WriteLine("成功插入" + res + "条数据");
            }

 

四、插入多条数据

            using (var conn = Dbhelper.GetConnection())
            {
                int res = conn.Execute("insert into t_student(`name`,`sex`,`age`) values(@name,@sex,@age)", 
                    new[] {
                        new { name = "张三", sex = 1, age = 23 },
                        new { name = "李四", sex = 1, age = 30 }
                    }
                
                );
                Console.WriteLine("成功插入" + res + "条数据");
            }

二、Dapper,向数据库中增加数据