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();
}
}
新聞熱點
疑難解答