二、SqlCommand操作数据库

1.ExecuteNonQuery:执行非查询的T-SQL语句

 using (SqlCommand cmd = conn.CreateCommand())
 {
      cmd.CommandText = "insert into userInfo(id,userName,userAge,DelFlag)values(11,'赵非',18,0)";
      //设置T-SQL语句
      int num = cmd.ExecuteNonQuery();
      //执行T-SQL语句,并返回受影响的行数
      Console.WriteLine(num);
 }

2.ExecuteScalar:执行查询,并返回查询所返回的结果集中第一行的第一列

 using (SqlCommand cmd = conn.CreateCommand())
 {
      cmd.CommandText = "select * from Employee where gender='男' ";
      //查询Employee表中性别为男的所有信息
      label1.Text = cmd.ExecuteScalar().ToString();
      //执行查询,并返回这些信息中的第一行的第一列的数据
 }

 3.ExecuteReader:执行T-SQL语句,并返回一个SqlDataReader读取器

using (SqlCommand cmd = conn.CreateCommand())
{
      cmd.CommandText = "select * from employee";
      SqlDataReader reader = cmd.ExecuteReader();
      //执行T-SQL语句,并生成一个SqlDataReader读取器
      while (reader.Read())
      {
         listView1.Items.Add(reader[1].ToString());
      }
      //reader[1]:读取表中第2列的数据
      reader.Close();
}

猜你喜欢

转载自www.cnblogs.com/wby94510/p/9231011.html