Web Wiz - Green Windows Web Hosting

  New Posts New Posts RSS Feed - Creating database from code
  FAQ FAQ  Forum Search   Events   Register Register  Login Login

Creating database from code

 Post Reply Post Reply Page  12>
Author
theSCIENTIST View Drop Down
Senior Member
Senior Member


Joined: 31 July 2003
Location: United Kingdom
Status: Offline
Points: 440
Post Options Post Options   Thanks (0) Thanks(0)   Quote theSCIENTIST Quote  Post ReplyReply Direct Link To This Post Topic: Creating database from code
    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?
Back to Top
michael View Drop Down
Senior Member
Senior Member
Avatar

Joined: 08 April 2002
Location: United States
Status: Offline
Points: 4670
Post Options Post Options   Thanks (0) Thanks(0)   Quote michael Quote  Post ReplyReply Direct Link To This Post 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
Back to Top
theSCIENTIST View Drop Down
Senior Member
Senior Member


Joined: 31 July 2003
Location: United Kingdom
Status: Offline
Points: 440
Post Options Post Options   Thanks (0) Thanks(0)   Quote theSCIENTIST Quote  Post ReplyReply Direct Link To This Post 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.
Back to Top
michael View Drop Down
Senior Member
Senior Member
Avatar

Joined: 08 April 2002
Location: United States
Status: Offline
Points: 4670
Post Options Post Options   Thanks (0) Thanks(0)   Quote michael Quote  Post ReplyReply Direct Link To This Post 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
Back to Top
michael View Drop Down
Senior Member
Senior Member
Avatar

Joined: 08 April 2002
Location: United States
Status: Offline
Points: 4670
Post Options Post Options   Thanks (0) Thanks(0)   Quote michael Quote  Post ReplyReply Direct Link To This Post Posted: 05 October 2006 at 7:07pm
oops that was drop, make it IF NOT EXISTS and CREATE
Back to Top
theSCIENTIST View Drop Down
Senior Member
Senior Member


Joined: 31 July 2003
Location: United Kingdom
Status: Offline
Points: 440
Post Options Post Options   Thanks (0) Thanks(0)   Quote theSCIENTIST Quote  Post ReplyReply Direct Link To This Post 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.


Edited by theSCIENTIST - 05 October 2006 at 9:42pm
Back to Top
michael View Drop Down
Senior Member
Senior Member
Avatar

Joined: 08 April 2002
Location: United States
Status: Offline
Points: 4670
Post Options Post Options   Thanks (0) Thanks(0)   Quote michael Quote  Post ReplyReply Direct Link To This Post 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>


Edited by michael - 05 October 2006 at 10:23pm
Back to Top
Mart View Drop Down
Senior Member
Senior Member
Avatar

Joined: 30 November 2002
Status: Offline
Points: 2304
Post Options Post Options   Thanks (0) Thanks(0)   Quote Mart Quote  Post ReplyReply Direct Link To This Post 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
Back to Top
 Post Reply Post Reply Page  12>

Forum Jump Forum Permissions View Drop Down

Forum Software by Web Wiz Forums® version 12.08
Copyright ©2001-2026 Web Wiz Ltd.


Become a Fan on Facebook Follow us on X Connect with us on LinkedIn Web Wiz Blogs
About Web Wiz | Contact Web Wiz | Terms & Conditions | Cookies | Privacy Notice

Web Wiz is the trading name of Web Wiz Ltd. Company registration No. 05977755. Registered in England and Wales.
Registered office: Web Wiz Ltd, Unit 18, The Glenmore Centre, Fancy Road, Poole, Dorset, BH12 4FB, UK.

Prices exclude VAT at 20% unless otherwise stated. VAT No. GB988999105 - $, € prices shown as a guideline only.

Copyright ©2001-2026 Web Wiz Ltd. All rights reserved.