Print Page | Close Window

Creating database from code

Printed From: Web Wiz Forums
Category: General Discussion
Forum Name: ASP.NET Discussion
Forum Description: Discussion and chat on ASP.NET related topics.
URL: https://forums.webwiz.net/forum_posts.asp?TID=21488
Printed Date: 28 March 2026 at 5:31pm
Software Version: Web Wiz Forums 12.08 - https://www.webwizforums.com


Topic: Creating database from code
Posted By: theSCIENTIST
Subject: Creating database from code
Date Posted: 05 October 2006 at 6:11am
Hi guys, been all night trying to create a SQL server database from asp.net code, and no joy, googled for it, again no references to it.
 
I can use Enterprise Manager and create the database, but I would like my applications to be able to create the DB also.
 
Heres the code that dont work:
 

<%@ Page Language="VB" Debug="true" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<Script RunAt="server">
    '// System.Data.OleDb
    '// Initial Catalog=Northwind
    '// DATABASE=Northwind
    '// Trusted_Connection=False
    Sub Page_Load(ByVal o As Object, ByVal e As EventArgs)
        Dim db_Name As String = "db_MLH"
        '// Dim ConnectionString As String = "Data Source=localhost;User ID=********;Password=********;"
        Dim ConnectionString As String = "SERVER=localhost;UID=********;PWD=********;"
        Dim mlhConn As SqlConnection = New SqlConnection(ConnectionString)
        mlhConn.Open()
        Dim strSQL as String = "CREATE DATABASE IF NOT EXISTS " & db_Name & ";"
        Dim objCommand As SqlCommand = New SqlCommand(strSQL, mlhConn)
        '// objCommand.Connection = mlhConn
        '// objCommand.CommandText = "CREATE DATABASE IF NOT EXISTS " & db_Name & ";"
        mlhConn.Close()
        lblStatus.Text &= "<br /><br />DB created"
    End Sub
</Script>
 
<html>
<head runat="server">
    <title>LOCALHOST</title>
</head>
<body>
<asp:label id="lblStatus" runat="server" />
</body>
</html>
 
Notice that my connection string dont have a database specified, I think this is not needed as I am just connecting to the server to create a database, I will then close the connection and connect again to the newly created database so I can go on creating tables and inserting default values. Please advise on best approach?
 
Also what namespace should I import [System.Data.SqlClient] or [System.Data.OleDb] what's the difference or fastest methods?
 
Anyone can make this code work?


-------------
:: http://www.mylittlehost.com/ - www.mylittlehost.com



Replies:
Posted By: michael
Date Posted: 05 October 2006 at 2:29pm
When creating a database I would always specify the master database, I don't think you can get away with just not specifying any.

Also your IF NOT EXISTS syntax does not look right... Should be
If Not Exists (Select......)
Create Database somedbname

-------------
http://baumannphoto.com" rel="nofollow - Blog | http://mpgtracker.com" rel="nofollow - MPG Tracker


Posted By: theSCIENTIST
Date Posted: 05 October 2006 at 4:53pm
Michael, I thought SQL conventions dictated all upper case and not camel case as you suggested, anyway, can you please repost your create statement as I tried a few combinations and none worked. Something is up and I don't think its the create statement.
 
Here's my current code, have a look:
 

<%@ Page Language="VB" Debug="true" %>
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script runat="server">
    Sub Page_Load(o as Object, e as EventArgs)
        Dim ConnectionString As String = "Server=localhost;Database=master;User ID=********;Password=********;"
        Dim myConnection As New SqlConnection(ConnectionString)
        Dim db_Name As String = "db_MLH"
        Dim strSQL As String = "Create Database " & db_Name & ";"
        Dim myCommand As New SqlCommand(strSQL, myConnection)
        myConnection.Open()
        myConnection.Close()
        lblStatus.Text = "DB created"
    End Sub
</script>
<asp:label id="lblStatus" runat="server" />
 
Can anyone try this code to create a SQL server database? Even on 'borgs' code of these forums, he asks people to create a database and his not doing it from code.
 
There's a few things I don't know;
 
     1. The user will connect to the 'master' db what about if he doesn't have access to it? I gave the user access anyway for testing, of no avail. Do I realy have to connect to 'master' to create another db?
 
     2. My connection string, I tried both types; 'data source' and 'server' which one is the correct one?
 
     3. Is my db open/close approach correct for this purpose?
 
     4. How do I get to know/see/catch errors in the connection?
 
Thanks guys.


-------------
:: http://www.mylittlehost.com/ - www.mylittlehost.com


Posted By: michael
Date Posted: 05 October 2006 at 7:07pm
IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name =
N'dbname')
        DROP DATABASE [dbname]

I think the statement you had used is mySQL Syntax

-------------
http://baumannphoto.com" rel="nofollow - Blog | http://mpgtracker.com" rel="nofollow - MPG Tracker


Posted By: michael
Date Posted: 05 October 2006 at 7:07pm
oops that was drop, make it IF NOT EXISTS and CREATE

-------------
http://baumannphoto.com" rel="nofollow - Blog | http://mpgtracker.com" rel="nofollow - MPG Tracker


Posted By: theSCIENTIST
Date Posted: 05 October 2006 at 9:38pm
Yes, I use to work alot with MySQL, making the move to SQL server as most Companies ask for it when it comes to ASP.NET.
 
Well, thx but still don't work.
 
Lets forget about the IF NOT EXISTS bit, as I will check that part later, lets focus on the create database only, i tried this:
 
"CREATE DATABASE [db_Name];"
"CREATE DATABASE ['db_Name'];"
"CREATE DATABASE [" & db_Name & "];"
"CREATE DATABASE db_Name;"
"CREATE DATABASE 'db_Name';"
"CREATE DATABASE " & db_Name & ";"
 
None work, any hints?
 
Can anyone actually try the code, as I think something is wrong elsewhere.


-------------
:: http://www.mylittlehost.com/ - www.mylittlehost.com


Posted By: michael
Date Posted: 05 October 2006 at 10:22pm
Keeping it simple, but this code (I tested) works
<%@ Page Language="VB" %>

<script runat="server">

    Protected Sub buttonCreateDatabase_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim con As New Data.SqlClient.SqlConnection("Server=(local);Database=master;User ID=sa;Password=***;")
        Dim cmd As New Data.SqlClient.SqlCommand(String.Format("Create Database [{0}]", textboxDBName.Text), con)
        Try
            con.Open()
            cmd.ExecuteNonQuery()
        Catch ex As System.Data.SqlClient.SqlException
            errorLabel.Text = "Error executing Statement: " & ex.Message
        End Try
    End Sub
</script>
<html>
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="textboxDBName" runat="server"></asp:TextBox>
        <asp:Button ID="buttonCreateDatabase" runat="server" OnClick="buttonCreateDatabase_Click"
            Text="Create Database" /><br />
        <asp:Label ID="errorLabel" runat="server"></asp:Label></div>
    </form>
</body>
</html>


-------------
http://baumannphoto.com" rel="nofollow - Blog | http://mpgtracker.com" rel="nofollow - MPG Tracker


Posted By: Mart
Date Posted: 06 October 2006 at 3:24pm
Just a quick pointer just incase you didn't know: the sql server account you use to connect needs to have the correct permission to create databases


Posted By: theSCIENTIST
Date Posted: 06 October 2006 at 11:48pm
Thanks Michael, it works fine, however I'm puzzled why my code didn't and I think the problem may lay in this:
 
In your connection string, it is like this: Server=(local) and in mine it was Server=localhost, maybe this was the problem, also what is this: Create Database [{0}] whats the funny 0 doing there?
 
I gave this user permissions to create databases, as it stands this user is also a dba, I will remove priviledges untill the user can only create databases and do all the normal operations with it. I don't think the user need access to the master database, but will try removing it, if he does this could be a problem as users could then access this crutial database just to create another database.
 
Thanks guys.


-------------
:: http://www.mylittlehost.com/ - www.mylittlehost.com


Posted By: Mart
Date Posted: 07 October 2006 at 8:05am
Basically Server=Localhost will only work for the full SQL Server 2000 edition. (local) will work for both MSDE and SQL Server 2000 connection strings.

The {0} is a format string. Basically what it is saying is place the value of the first parameter to the string.Format function here... i.e.

string helloWorld = string.Format("Hello {0}!", "world");

is equivalent to

string helloWorld = "Hello world!";

It just saves a lot of string concatation


Posted By: theSCIENTIST
Date Posted: 07 October 2006 at 8:40am
Ahh, got it, 0 would be 'world' as in first element of an arrays.
 
Thanks guys.


-------------
:: http://www.mylittlehost.com/ - www.mylittlehost.com



Print Page | Close Window

Forum Software by Web Wiz Forums® version 12.08 - https://www.webwizforums.com
Copyright ©2001-2026 Web Wiz Ltd. - https://www.webwiz.net