2013-07-27 144 views
0

我正在尝试通过动态地通过VB.net下面的代码创建数据库动态

Dim str As String 
Dim myConn As SqlConnection = New SqlConnection("Server=(local)\netsdk;" & _ 
            "uid=sa;pwd=a123;database=master") 

str = "CREATE DATABASE MyDatabase ON PRIMARY " & _ 
     "(NAME = MyDatabase_Data, " & _ 
     " FILENAME = 'E:\MyDatabaseData.mdf', " & _ 
     " SIZE = 2MB, " & _ 
     " MAXSIZE = 10MB, " & _ 
     " FILEGROWTH = 10%) " & _ 
     " LOG ON " & _ 
     "(NAME = MyDatabase_Log, " & _ 
     " FILENAME = 'E:\MyDatabaseLog.ldf', " & _ 
     " SIZE = 1MB, " & _ 
     " MAXSIZE = 5MB, " & _ 
     " FILEGROWTH = 10%) " 

Dim myCommand As SqlCommand = New SqlCommand(str, myConn) 

Try 
    myConn.Open() 
    myCommand.ExecuteNonQuery() 
    MessageBox.Show("Database is created successfully", _ 
        "MyProgram", MessageBoxButtons.OK, _ 
        MessageBoxIcon.Information) 
Catch ex As Exception 
    MessageBox.Show(ex.ToString()) 
Finally 
    If (myConn.State = ConnectionState.Open) Then 
     myConn.Close() 
    End If 
End Try 

创建数据库,但我有以下错误,当项目运行:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

+0

你的con字符串应该是'(localdb)'而不是'(local)'? – 2013-07-27 01:26:53

+0

错误仍然显示 – mhmad

回答

2

你需要有您使用的连接字符串中具有相同名称的实际服务器实例上运行:

Dim myConn As SqlConnection = New SqlConnection("Server=(local)\netsdk;" & _ 
             "uid=sa;pwd=a123;database=master") 

我在这种情况下,它是(local)\netsdk,而且您显然没有在执行此代码的计算机上安装名为netsdk的SQL Server实例。

+0

更多信息请 – mhmad

+1

**必须在计算机上运行具有该名称的服务器实例**。我不知道如何更具体。如果系统上没有名为'(local)\ netsdk'的SQL Server实例,则无法在其中创建数据库。如果没有一个叫玛丽的女人,我不能把一个男孩称为“玛丽的儿子”。 –

+0

看我需要通过VB创建数据库的方式,所以在我使用我的应用程序后,无需在计算机上运行它应用程序SQL Server – mhmad

1
New SqlConnection("Server=(local)\netsdk;" 

这就是说你的应用必须连接到你的机器上运行的SQL Server实例。

my Application run it App on computer without need SQL Server

违背你的代码怎么说。它也与你的问题中的sql-server标签相矛盾。你在建什么样的应用程序? Windows桌面应用程序?的WinForms?

如果您正在构建必须在没有安装数据库的情况下运行的单机应用程序,则应使用嵌入式数据库,如SQL Compact。数据库在应用程序内部运行,不需要运行单独的实例。

SQL Compact的连接字符串与您所显示的不同,您需要按照教程进行操作。点击SQL Compact页面中的“学习中心”。