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();