用過VS2005和VS2008的開發人員肯定知道在安裝這個IDE的時候會自動安裝了一個精簡版的SQL資料庫服務SqlExpress,這個資料庫系統少了最重要的企業管理器,也就是說不能用它來建資料表和一些可視化操作。如果碰到項目中要用到SQL資料庫的時候也不能附加到資料庫服務裡面去,導致項目在串連資料庫的時候會提示找不到資料庫檔案而讀取失敗。那麼,這個精簡版的SQL資料庫服務是不是意味著一無是處呢?
其實未必,只要我們在串連資料庫的時候利用好它就可以了~~
在這裡我介紹兩種C#中串連資料庫的方法。一種需要附加資料庫,一種則不要,只需要安裝這個精簡版的SQL就可以了…
方法一:
串連代碼:
string strconn;
strconn = "Data Source=(local);";
strconn += "Initial Catalog=student;";
strconn += "User ID=sa;";
strconn += "Password=;";
SqlConnection con = new SqlConnection(strconn); //通過使用者名稱和密碼串連資料庫
//SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=library;Integrated Security=True"); //通過系統使用者驗證串連資料庫
con.Open();
SqlDataAdapter thisadapter = new SqlDataAdapter("select * from reader where 條碼='" + txm + "'", con);
SqlCommandBuilder thisbuilder = new SqlCommandBuilder(thisadapter);
DataSet thisdataset = new DataSet();
thisadapter.Fill(thisdataset, "reader");
…… //接下去就是對資料的操作了
這種方法必須要附加資料庫檔案才可以訪問…
優點是可以通過企業管理器直接對資料庫進行可視化操作,比如對記錄進行全權修改…萬一碰到資料有錯誤,在系統裡面不好修改的時候可以進行強制維護。同時,如果後期更新系統,增加新的資料庫需求,比如增加欄位就可以在裡面操作。
當然這也算是缺點,亂改資料可能導致破壞資料庫的一些規則和資料一致性,嚴重的話會導致災難性的資料崩潰。
方法二:
串連代碼:
SqlConnectionStringBuilder connectstringbuilder = new SqlConnectionStringBuilder();
connectstringbuilder.DataSource = @"(local)"sqlexpress"; //指定資料庫服務
connectstringbuilder.AttachDBFilename = @"|DataDirectory|"data"library.mdf"; //資料庫檔案,採用相對位址的方式來指定。注意格式
connectstringbuilder.IntegratedSecurity = true;
connectstringbuilder.UserInstance = true;
SqlConnection thisconnection = new SqlConnection(connectstringbuilder.ConnectionString);
SqlDataAdapter thisadapter = new SqlDataAdapter("select * from reader where 條碼='" + txm + "'", thisconnection);
DataSet dt = new DataSet();
thisadapter.Fill(dt, "info");
…… //接下去就是對資料的操作了
這個方法最大的優點就是允許我們不用安裝600M(MSSQL2000)或者1G(MSSQL2005)的資料庫系統,只需要安裝SQL精簡版的資料庫服務(22M左右)就可以了。而且不用去附加資料庫…
但是這種優點也帶來致命的缺點,就是第一次串連資料庫的時候會有點慢,這不要緊,但它會重新格式資料庫檔案的一些結構,導致一些資料格式發生變化,因此串連之後這樣的資料庫檔案是不能再次被附加到資料庫系統中的(會報錯)。也就是說後期如果要修改資料庫,比如增加欄位和表等是不太可能實現的。
不過這也在一定的程度上帶來了安全性。