classProgram { staticvoidMain(string[] args) { List<Person> res; using (IDbConnection cnn = new MySqlConnection(LoadConnectString())) { cnn.Open(); res = cnn.Query<Person>("select * from PERSON where age>=80").ToList(); } Console.WriteLine("ID\t\tNAME\t\tAGE\t\tADDRESS\t\tSALARY"); foreach (var v in res) Console.WriteLine($"{v.Id }\t\t{v.Name}\t\t{v.Age}\t\t{v.Address}\t\t{v.Salary}"); Console.ReadKey(); }
privatestaticstringLoadConnectString(string id = "testdb01") { return ConfigurationManager.ConnectionStrings[id].ConnectionString; } }
///<summary> /// 从数据库中查询数据 ///</summary> ///<typeparam name="T">与数据库中表对应的类</typeparam> ///<param name="dbPath">数据库的绝对路径</param> ///<param name="sql">查询字符串,示例:"select * from PERSON where age>=80"</param> ///<returns></returns> publicList<T> QueryData<T>(string sql) { List<T> res = null; using (IDbConnection cnn = new SQLiteConnection(GetConnectString(dbPath))) { cnn.Open(); res = cnn.Query<T>(sql, new DynamicParameters()).ToList(); } return res; }
///<summary> /// 从数据库中删除数据 ///</summary> ///<param name="dbPath">数据库名绝对路径</param> ///<param name="sql">执行删除的SQL语句,示例:"delete from PERSON where age>=70"</param> ///<returns></returns> publicboolDeleteData(string sql) { int res = 0; using (IDbConnection cnn = new SQLiteConnection(GetConnectString(dbPath))) { cnn.Open(); res = cnn.Execute(sql); } return res > 0; }
///<summary> /// 向数据库中插入信息 ///</summary> ///<typeparam name="T">与表对应的类</typeparam> ///<param name="sql">插入信息的语句,示例:"insert into PERSON(id,name,age,address,salary) values(@Id,@Name,@Age,@Address,@Salary)"</param> ///<param name="t">要插入的对象</param> ///<returns></returns> publicboolInsertData<T>(string sql, T t) { int res = 0; using (IDbConnection cnn = new SQLiteConnection(GetConnectString(dbPath))) { cnn.Open(); res = cnn.Execute(sql, t); } return res > 0; }
///<summary> /// 向数据库中插入信息 ///</summary> ///<typeparam name="T">与表对应的类</typeparam> ///<param name="sql">更新SQL语句:"update PERSON set name=@Name,age=@Age,address=@Address,salary=@Salary where id=10000",</param> ///<param name="t">要更新的信息</param> ///<returns>成功返回true</returns> publicboolUpdateData<T>(string sql, T t) { int res = 0; using (IDbConnection cnn = new SQLiteConnection(GetConnectString(dbPath))) { cnn.Open(); res = cnn.Execute(sql, t); } return res > 0; } }
staticvoidMain(string[] args) { DapperDBOperator op = new DapperDBOperator(@"C:\testDB01.db"); //删 op.DeleteData("delete from PERSON where age>=60"); //查 var res = op.QueryData<Person>("select * from PERSON where age>=50"); foreach (var v in res) Console.WriteLine($"{v.Id }\t\t{v.Name}\t\t{v.Age}\t\t{v.Address}"); //增 Person p = new Person(); p.Id = 100000; p.Name = "lihao"; p.Age = 29; p.Salary = 20000; p.Address = "wuhanshi"; op.InsertData<Person>("insert into PERSON(id,name,age,address,salary) values(@Id,@Name,@Age,@Address,@Salary)", p); //改 p.Salary = 40000; op.UpdateData<Person>("update PERSON set name=@Name,age=@Age,address=@Address,salary=@Salary where id=100000", p); Console.ReadKey(); }