First, create a "student" table (note, the database used in this article is MySQL)
CREATE TABLE ' t_student ' ( ' id ' int (one) not null auto_increment, ' name ' varchar (6) NOT null DEFAULT ' COMMENT ' name ', ' sex ' bit (1) NOT null default B ' 0 ' COMMENT ' sex, 0 means female, 1 is male ', ' age ' tinyint (3) ' is not null default ' 0 ' COMMENT ' ages ', C4/>primary KEY (' id ')) engine=innodb DEFAULT charset=utf8 comment= ' student ';
Second, write a "" class, Inside to achieve database connection related
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>///Connection class//</summar Y> public class DBHelper {//<summary>///MySQL connection string///</summary> PU Blic static string mysqlconnectionstring = "Server=localhost;user id=root;password=root;database=dapper;port=3306; Character Set=utf8 "; private static idbconnection connection; <summary>//Get DB connection///</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; } }}
Iii. inserting a single piece of data
using (var conn = dbhelper.getconnection ()) { int res = conn. Execute ("INSERT into t_student (' name ', ' sex ', ' age ') VALUES (@name, @sex, @age)", new {name = "Zhang San", sex = 1, age = All}); Console.WriteLine ("Insert successfully" + res + "bar data"); }
Iv. inserting more than one piece of data
using(varconn =dbhelper.getconnection ()) { intRES = conn. Execute ("INSERT INTO t_student (' name ', ' sex ', ' age ') VALUES (@name, @sex, @age)", New[] { New{name ="Zhang San", sex =1, age = at }, New{name ="John Doe", sex =1, age = - } } ); Console.WriteLine ("successfully inserted"+ res +"Bar Data"); }
Ii. Dapper, adding data to the database