概要 程序員常常需要以編程方式創建數據庫。本文介紹如何使用 ADO.NET 和 Visual Basic .Net 以編程方式創建 Microsoft SQL
創建示例的步驟 1.新建一個 Visual Basic .Net Windows 應用程序項目。默認情況下,將 Form1 添加到項目中。
2.在 Form1 上放一個 Command 按鈕,並將其 Name 屬性更改為 btnCreateDatabase,將其 Text 屬性更改為 Create Database。
3.復制下面一行代碼並粘貼到 Form1 的“general declaration”部分: Imports System.Data.SqlClIEnt
4.復制下面的代碼並粘貼到“Windows Form Designer generated code”區域之後:
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCreateDatabase.Click
Dim reader As SqlDataReader
Dim str As String
Dim myConn As SqlConnection = New SqlConnection("Server=(local)
etsdk;" & _
"uid=sa;pwd=;database=master")
str = "CREATE DATABASE MyDatabase ON PRIMARY " & _
"(NAME = MyDatabase_Data, " & _
" FILENAME = 'D:MyFolderMyDatabaseData.mdf', " & _
" SIZE = 2MB, " & _
" MAXSIZE = 10MB, " & _
" FILEGROWTH = 10%) " & _
" LOG ON " & _
"(NAME = MyDatabase_Log, " & _
" FILENAME = 'D:MyFolderMyDatabaseLog.ldf', " & _
" SIZE = 1MB, " & _
" MAXSIZE = 5MB, " & _
" FILEGROWTH = 10%) "
Dim myCommand As SqlCommand = New SqlCommand(str, myConn)
Try
myConn.Open()
reader = myCommand.ExecuteReader()
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
If Not reader Is Nothing Then
reader.Close()
If (myConn.State = ConnectionState.Open) Then
myConn.Close()
End If
MessageBox.Show("Database is created successfully", _
"MyProgram", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
End If
End Try
End Sub
5.更改連接字符串使其指向 SQL Server,要確保將 Database 參數設置為 Master 或保留為空白。
6.按 F5 鍵或 CTRL+F5 組合鍵以運行該項目,然後單擊創建數據庫。
其他注意事項 此代碼創建的是帶有特定屬性的自定義數據庫。
將要保存所創建 .mdf 和 .ldf 文件的文件夾必須在運行該代碼之前就已存在、否則會引發異常。
如果想創建一個類似於 SQL Server 的 Model 數據庫的數據庫並想讓它存儲在默認位置,那麼請更改代碼中的 str 變量: str = "CREATE DATABASE MyDatabase"