.NET和VB编程创建SQL Server

时间:2010-01-27 11:10:17  来源:第二电脑网  作者:第二电脑网

  第二电脑网导读:并粘贴到 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
  正文:

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: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"

.NET和VB编程创建SQL Server》由第二电脑网原创提供,转载请注明:http://www.002pc.com/master/College/Language/VB/12473.html


关键字:

关于《.NET和VB编程创建SQL Server》文章的评论

站内搜索: 高级搜索

热门搜索: Windows style 系统 tr IP QQ CPU 安装 function 注册 if td