1. 程式人生 > >數據庫第十三章使用ADO.NET訪問數據庫

數據庫第十三章使用ADO.NET訪問數據庫

all ole exce cti lin string 數據庫 mman catch


string sqlcon="Data Source=.;Initial Calalog=MySchool;User ID=sa;Pwd=.";


Connection:打開數據庫連接
程序與數據庫溝通的橋梁

SqlConnection con=new SqlConnection(sqlcon);
try
{
//可能發生異常的代碼
con.Open();
}
catch(Exception ex)
{
//捕獲異常
Console.WriteLine(ex);
}
finally
{
con.Close();
//永遠都會被執行
}


Command:向數據庫發送命令,提交SQL命令並從數據源中返回結果
string sql="select count(*) from Student where StudentNo=‘"+username+"‘ and LoginPwd=‘"+password+"‘";
//向數據庫發送一條SQL語句
SqlCommand command=new SqlCommand(sql,con);
//結果
int count=(int)command.ExecuteScalar();
if(count>0)
{
Console.WriteLine("登錄成功");

}else
{
Console.WriteLine("查無此人");
}

數據庫第十三章使用ADO.NET訪問數據庫