1、ExecuteNonQuery()//返回受影响行数,如果多条就会累加
string connStr = @"server=WIN-20161229QGK\SQLEXPRESS;uid=PJ;pwd=123;database=MySchoolMoreData";
using (SqlConnection conn=new SqlConnection (connStr))
{
conn.Open();
string sql = string.Format("insert into grade values('{0}');select count(*)from grade",textBox1.Text.Trim ());
SqlCommand command = new SqlCommand(sql,conn);
int num = (int)command.ExecuteNonQuery();
MessageBox.Show(num.ToString());
}
2、ExecuteScalar()//返回查询结果的第一行第一列的值
string connStr = @"server=WIN-20161229QGK\SQLEXPRESS;uid=PJ;pwd=123;database=MySchoolMoreData";
using (SqlConnection conn=new SqlConnection (connStr))
{
conn.Open();
string sql = string.Format("insert into grade values('{0}');select count(*)from grade",textBox1.Text.Trim ());
SqlCommand command = new SqlCommand(sql,conn);
int num = (int)command.ExecuteScalar();
MessageBox.Show(num.ToString());
}
3、ExecuteReader()//读取数据表,并存入缓存,就是数据读取器。把数据一条条的读出
string connStr = @"server=WIN-20161229QGK\SQLEXPRESS;uid=PJ;pwd=123;database=MySchoolMoreData";
using (SqlConnection conn=new SqlConnection (connStr))
{
conn.Open();
string sql = "select classid,classname from grade";
SqlCommand command = new SqlCommand(sql,conn);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())//判断有没有下一个数据,类似于迭代器
{
ListViewItem lv = new ListViewItem(reader["classid"].ToString());
lv.SubItems.Add(reader["classname"].ToString());
listView1.Items.Add(lv);
}
}