声明一个类,在类中实现增删查改的方法
public class AdoNet { //声明连接字符串 public string Sqlstr = "data source={0};database={1};User id={2};pwd={3}"; //声明ado类 public SqlCommand Command; public SqlConnection Conn; //声明构造函数 传入连接字符串进行拼接 public AdoNet(string datasource,string database, string userid,string pwd) { var cStr = string.Format(Sqlstr, datasource, database, userid, pwd); Conn = new SqlConnection(cStr); } //增加 public void AdonetAdd(string cmd) { //打开数据库 Conn.Open(); //使用using 在命令执行完后会释放资源 using (SqlCommand sqlcmd = new SqlCommand(cmd,Conn)) { //获取要执行的sql语句 sqlcmd.CommandText= cmd; if (sqlcmd.ExecuteNonQuery() > 0) { Console.WriteLine("增加成功"); } else { Console.WriteLine("增加失败"); } } } //删除 public void AdoDelete(string cmd) { Conn.Open(); using (SqlCommand sqlcmd = new SqlCommand(cmd, Conn)) { sqlcmd.CommandText = cmd; if (sqlcmd.ExecuteNonQuery() > 0) { Console.WriteLine("删除成功"); } else { Console.WriteLine("删除失败"); } } } //查询 public void AdoNetState(string cmd) { Conn.Open(); Command = new SqlCommand(cmd, Conn); //批量查询 SqlDataAdapter ad = new SqlDataAdapter(Command); DataTable dt = new DataTable(); ad.Fill(dt); var s1= dt.Select(); var arrlist1 = s1[0].ItemArray[0]; var arrlist2 = s1[0].ItemArray[1]; var arrlist3 = s1[1].ItemArray[0]; var arrlist4 = s1[1].ItemArray[1]; Console.WriteLine(arrlist1); Console.WriteLine(arrlist2); Console.WriteLine(arrlist3); Console.WriteLine(arrlist4); //单条查询 //SqlDataReader dataAdapter = Command.ExecuteReader(); //while (dataAdapter.Read()) //{ // Console.WriteLine("{0}", dataAdapter["FieldName"]); //} Console.ReadKey(); } //改 public void AdoEdit(string cmd) { Conn.Open(); using (SqlCommand sqlcmd=new SqlCommand(cmd,Conn)) { sqlcmd.CommandText = cmd; if (sqlcmd.ExecuteNonQuery() > 0) { Console.WriteLine("修改成功"); } else { Console.WriteLine("修改失败"); } } } }
在控制台入口声明sql语句 调用增删查改的方法
static void Main(string[] args) { //sql连接字符串 var adoNet = new AdoNet(".","Ttest","sa","123456"); ////调用查询方法 //var sqlstr = "select * from Field"; //adoNet.AdoNetState(sqlstr); //增加 //string strsql = "insert into Field(FieldName)values(‘哈哈哈‘)"; //adoNet.AdonetAdd(strsql); //删除 // string strsql = "delete from Field where FieldName=‘哈哈哈‘"; //adoNet.AdoDelete(strsql); //修改 string strsql = "Update Field set FieldName=‘Lisa‘ where FieldName=‘meiName‘"; adoNet.AdoEdit(strsql); }
原文地址:https://www.cnblogs.com/shapaozi/p/8384344.html
时间: 2024-10-29 03:34:15