mhmad
mhmad

Reputation: 43

Create Database Dynamically

i am try to create database dynamically by VB.net by the following code

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

but I have the following error when the project run :

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)

Upvotes: 0

Views: 722

Answers (2)

Dour High Arch
Dour High Arch

Reputation: 21722

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

That says your app must connect to a SQL Server instance running on your machine.

my Application run it App on computer without need SQL Server

That contradicts what your code says. It also contradicts the sql-server tag in your question. What kind of app are you building? A Windows desktop app? Winforms?

If you are building a single-machine app that must run without an installed database you should use an embedded database like SQL Compact. The database runs inside your application and you do not need to run a separate instance.

The connection strings for SQL Compact are different from what you have shown, you will need to follow a tutorial. Click on "Learning Center" in the SQL Compact page.

Upvotes: 1

Ken White
Ken White

Reputation: 125757

You need to have an actual server instance running that has the same name you're using in your connection string:

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

In this case, it's (local)\netsdk, and you apparently don't have an instance of SQL Server named netsdk installed on the machine where you're executing this code.

Upvotes: 2

Related Questions