編程創(chuàng)建 SQL Server 數(shù)據(jù)庫
2024-07-21 02:21:21
供稿:網友
 
中國最大的web開發(fā)資源網站及技術社區(qū),
創(chuàng)建 sql server 數(shù)據(jù)庫的步驟
新建 visual c# .net windows 應用程序。 
在 form1 上放置一個按鈕。 將按鈕的 name 屬性更改為 btncreatedatabase,將 text 屬性更改為 create database。 
對 system 和 system.data 名稱空間使用 using 語句,這樣,以后就不需要在代碼中限定這些名稱空間中的聲明了。將下面的代碼添加到 form1 的“general declarations”部分: 
using system;
using system.data.sqlclient;
往回切換到“窗體”視圖,然后雙擊創(chuàng)建數(shù)據(jù)庫以添加 click 事件處理程序。將下面的代碼添加到處理程序: 
 string str;
 sqlconnection myconn = new sqlconnection ("server=localhost;integrated security=sspi;database=master");
 str = "create database mydatabase on primary " +
 "(name = mydatabase_data, " +
 "filename = 'c://mydatabasedata.mdf', " +
 "size = 2mb, maxsize = 10mb, filegrowth = 10%) " +
 "log on (name = mydatabase_log, " +
 "filename = 'c://mydatabaselog.ldf', " +
 "size = 1mb, " +
 "maxsize = 5mb, " +
 "filegrowth = 10%)";
 sqlcommand mycommand = new sqlcommand(str, myconn);
try 
 {
 myconn.open();
mycommand.executenonquery();
messagebox.show("database is created successfully", "myprogram", messageboxbuttons.ok, messageboxicon.information);
 }
 catch (system.exception ex)
 {
messagebox.show(ex.tostring(), "myprogram", messageboxbuttons.ok, messageboxicon.information);
 }
 finally
 {
if (myconn.state == connectionstate.open)
{
 myconn.close();
}
 }
更改連接字符串以指向您的 sql server 計算機,并確保 database 參數(shù)設置為 master 或為空。 
按 f5 鍵或 ctrl+f5 組合鍵以運行該項目,然后單擊創(chuàng)建數(shù)據(jù)庫。 
使用服務器資源管理器驗證數(shù)據(jù)庫創(chuàng)建。 
返回頁首 
備注: 
此代碼創(chuàng)建具有特定屬性的自定義數(shù)據(jù)庫。 
在運行代碼前,將存放所創(chuàng)建的 .mdf 和 .ldf 文件的文件夾必須已經存在,否則將生成異常。 
如果想創(chuàng)建一個類似于 sql server 的 model 數(shù)據(jù)庫的數(shù)據(jù)庫并想讓它存儲在默認位置,那么請更改代碼中的 str 變量: 
str = "create database mydatabase"