一、ADO.NET中的模型及对象
1、EexcuteNonQuery------>实现非查询操作(增删改)
sql语句查询非参数化
//连接字符串 string conStr = @"server=.;database=MyDataBase;uid=sa;pwd=sa"; //要执行的sql语句 string sql = "insert into MyDataBase(Id,Name,Age,Sex) values(1,‘曹操‘,500,‘m‘)"; //创建连接对象 using (SqlConnection conn = new SqlConnection(conStr)) { //第一种写法; //创建执行对象(执行sql语句) //using (SqlCommand cmd = new SqlCommand()) //{ // cmd.Connection = conn; // cmd.CommandText = sql; // //打开数据库 // conn.Open(); // //返回收影响的行数 // int count = cmd.ExecuteNonQuery(); // Console.WriteLine("{0}行收影响", count); //} //第二种写法 在构造函数中传入SQL语句和连接对象 using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); int count = cmd.ExecuteNonQuery(); Console.WriteLine("{0}行受影响", count); } } Console.ReadKey()
2、ExcuteScalar查询首行首列(返回Object类型)
// 提示用户输入用户名 Console.Write("Enter User Id:"); string userName = Console.ReadLine(); // 提示用户输入密码 Console.Write("Enter Password:"); string userPwd = Console.ReadLine(); //连接字符串 string conStr = @"server=.;databae=MyDataBase;uid=sa;pwd=sa"; //sql 语句 string sql = string.Format("select count(*) from Users where userName=‘{0}‘ and userPwd={1}", userName, userPwd); int count = 0; using (SqlConnection conn = new SqlConnection(conStr)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); //返回首行首列是Object类型 count = (int)cmd.ExecuteScalar(); } } if (count > 0) { Console.WriteLine("登录成功"); } else { Console.WriteLine("登录失败"); }
3、ExecuteRader逐行读取数据
//连接字符串 string conStr = @"server=.;database=MyDataBase;uid=sa;pwd=sa"; //sql语句 查询整张表的数据(逐行取) string sql = "select * from Data"; using (SqlConnection conn = new SqlConnection(conStr)) { using (SqlCommand cmd = new SqlCommand(sql, conn)) { conn.Open(); //一次一行数据来回读取数据 SqlDataReader reader = cmd.ExecuteReader(); using (reader)//每次向下读取一行 直到读取完为止 { Console.WriteLine("{0},{1},{2}", reader[0], reader[1], reader[2]); } while (reader.Read())//循环读取每一行数据 直到读取完为止 { List<string> list = new List<string>();//每读取一行 创建一行string类型 for (int i = 0; i < reader.FieldCount; i++)//循环遍历每一行数据的每一列数据 { list.Add(reader[i].ToString()); } Console.WriteLine(string.Join(",", list)); } } }
4、SqlDataAdapter读取数据集
string conStr = @"server=.;database=MyDataBase;uid=sa;pwd=sa"; string sql = "select * top 10 from Data"; DataSet ds = new DataSet(); using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conStr)) { adapter.Fill(ds); } //取出DataSet中的数据 //遍历取出DataSet ds中的每一个表 for (int i = 0; i < ds.Tables.Count; i++) { DataTable dt = ds.Tables[i]; //遍历DataTable dt中的每一行 for (int j = 0; j < dt.Rows.Count; j++) { DataRow row = dt.Rows[i]; List<string> list = new List<string>(); for (int k = 0; k < row.ItemArray.Length; k++) { list.Add(row.ItemArray[k].ToString()); } Console.WriteLine(string.Join(",",list)); } }
原文地址:https://www.cnblogs.com/Jenkin/p/8547460.html
时间: 2024-10-07 03:58:28