程序员常常需要以编程方式创建数据库。本文介绍如何使用 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)\netsdk;" & _
"uid=sa;pwd=;database=master")
str = "CREATE DATABASE MyDatabase ON PRIMARY " & _
"(NAME = MyDatabase_Data, " & _
" FILENAME = 'D:\MyFolder\MyDatabaseData.mdf', " & _
" SIZE = 2MB, " & _
" MAXSIZE = 10MB, " & _
" FILEGROWTH = 10%) " & _
" LOG ON " & _
"(NAME = MyDatabase_Log, " & _
" FILENAME = 'D:\MyFolder\MyDatabaseLog.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