1.先创建数据库连接字符串:
string strcon ="Data Source=.;Initial Catalog=schoolDB;Integrated Security=True";
2.创建SqlConnection对象,需要注意的是SqlConnection对象在using System.Data.SqlClient;命名空间中。
SqlConnection conn = new sqlConnection(strcon);
3.写Sql语句:
StringBuilder sb = new StringBuilder(); sb.AppendLine("select"); sb.AppendLine(" StudentNo "); sb.AppendLine(" StudentName "); sb.AppendLine(" Age "); sb.AppendLine(" from "); sb.AppendLine(" student ");
5.打开数据库连接:
conn.Open();
6.创建SqlCommand对象:
SqlCommand cmd = new SqlCommand(sb.ToString(),conn);
7.处理返回的结果:
SqlDatareader dr = cmd.ExecuteReader();
注意:
(1)如果返回结果是返回单行单列的结果:
int count = (int) cmd.ExecuteScalar();
(2)如果是增删改操作,返回受影响的行数:
int rel = cmd.ExecuteNonQuery();
8.遍历输出数据库表中的数据:
while(dr.Read()){ //利用字段名输出(字段名不区分大小写) Console.WriteLine("学号是:{0}",dr["StudentNo"].ToString()); //利用下标输出(下标从0开始) Console.WriteLine("姓名是:{0}",dr[1].ToString()); Console.WriteLine("年龄是:{0}",Convert.ToInt32(dr["Age"])); }
9.关闭DataReader对象:
dr.Close();
10.关闭连接:
conn.Close();