實現在C#中通過語句,查詢資料庫中的資料
SqlConnection con = null; //建立SqlConnection 的物件
try //try裡面放可能出現錯誤的程式碼
{
string str = "data source=.;initial catalog=資料庫名稱;user ID=登入名;pwd=密碼;";
con = new SqlConnection(str);
con.Open(); //開啟資料庫
//以上操作為登入資料庫的操作
string sql = "select 列名1,列名2,列名3,列名4,列名5 from QQuser where 查詢條件;
SqlCommand com = new SqlCommand(sql,con);
SqlDataReader read=com.ExecuteReader(); //用com(變數名)點上ExecuteReader()方法,該方法的型別是SqlDataReader型別
while (read.Read()) //變數名點上Read()方法. 用迴圈來保證能將資料庫中的資料全部讀取完畢
//如果資料庫中當前指標的下一行有資料則Read()方法返回true,如果沒有資料則返回false
{
int number = Convert.ToInt32(read["列名1"]);//查詢列名1的資料,方法為: read(變數名)["列名"]; 該方法返回的是object型別
string name = read["列名2"].ToString(); //如上
string revise = read["列名3"].ToString();
string Email = read["列名4"].ToString();
int day = Convert.ToInt32(read["列名5"]);
Console.WriteLine("{0}\t{1}\t{2}\t\t{3}\t\t{4}", number, name, revise,Email,day);
}
}
catch (Exception) //當try中有錯誤則執行catch中的程式碼,否則不執行
{
Console.WriteLine("網路異常!");
}
finally //無論如何都會執行finally中的程式碼
{
if(con!=null) //判斷con不為空
{
con.Close();
}
}