1

I've got the following

SqlCommand cmd = getSQLCommand();
using (cmd.Connection)
using (cmd)
{
    try
    {
        string dbName = txt_DatabaseName.Text;
        var createDatabaseQuery = "exec ('CREATE DATABASE ' + @databaseName)";
        var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);
        sqlCommand.Parameters.Add("@databaseName", SqlDbType.Text);
        sqlCommand.Parameters["@databaseName"].Value = dbName.ToString();

        cmd.Connection.Open();

        sqlCommand.ExecuteNonQuery();
    }
    catch (SqlException ex)
    {
        Console.WriteLine(ex.ToString());
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('SQL Error. Record not added.')", true);
    }
    finally
    {
        cmd.Connection.Close();
    }
}

I'm fully aware that params are not supported in DDL operations, so I've got this really cool thread that I've been using to help me write the contents within the "try". How to use SqlCommand to CREATE DATABASE with parameterized db name?

That said, I'm still getting an exception error for incorrect syntax near 'Database'. This might be a user error but I've been stuck around this for an hour or so now.

Any thoughts/ improvements?

p.s. All I'm trying to do is to create a database programmatically by using a dynamic value of whatever happens to be in txt_DatabaseName.Text (and yes I will try to error handle this in case there's white spaces entered or any chars that are not supported in SQL.

p.p.s Any articles that I can have a look at against sql injection attacks or any suggestions around constructing the method I have to prevent it? This is a simple exercise that I'm doing on my local machine, not public facing but still would like to get ahead of the game if possible.

12
  • 4
    Why you use exec and not simply "CREATE DATABASE " + dbName.ToString()? Commented Jul 18, 2017 at 12:09
  • I still get Message = "Incorrect syntax near 'DATABASE'." Commented Jul 18, 2017 at 12:13
  • but if I do something simple "CREATE DATABASE TEST" it works just fine.. it's the syntax of the "CREATE DATABASE " + dbName.ToString(); that is doesn't like Commented Jul 18, 2017 at 12:13
  • @TimSchmelter let me introduce you to SQL Injection. (Albeit as it is being substituted into a string parametrisation will not help here: the value needs to be carefully checked, however given the number of concatenations seen around here any – however futile – attempt at parametrisation should be seen positively) Commented Jul 18, 2017 at 12:14
  • 1
    Use SMO to create database objects etc, not raw ADO.NET Commented Jul 18, 2017 at 13:06

2 Answers 2

0

You don't need the exec part at all. Again you are getting error after removing exec cause you are wrapping your query in single quote 'CREATE DATABASE ' which is getting considered as string literal. It should just be

var createDatabaseQuery = string.Format("CREATE DATABASE {0}",DBnamevariable);
var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);
Sign up to request clarification or add additional context in comments.

5 Comments

I'm pretty certain that you can't use a parameter with CREATE DATABASE. Tha's DDL, not DML
@PanagiotisKanavos, real embarrassing ... thanks for pointing that. how I missed that !!!
Unless the OP performs some rigorous validation of DBnamevariable this will expose the server to SQL injection attacks
hmm very interesting! we have a different error var createDatabaseQuery = "CREATE DATABASE @databaseName)"; so it actually recognizes the Create Database command
@MrDedupe what is the value of the parameter? You are still concatenating strings. Any weird values, spaces, dots, etc will result in an invalid statement. Add a ; and you will execute two statements
0

Take a look with the sql profiler to see what is being fired against the database. If it is not working try to execute the query in Management studio to see it that is working. It's probably some kind of special character that is not allowed.

4 Comments

No need for the profiler, If i enter something simple like "CREATE DATABASE TEST" it works, it just doesn't understand the syntax if we do it with a variable rather than a hardcoded text. The catch method gives us the following error during debug ex = {"Incorrect syntax near 'DATABASE'."}
@MrDedupe who says it works? If you take a look look at the profiler you can see what your code is generating and firing against the database. Maybe it is doing something else that you didn't expect. its clearly not CREATE DATABASE TEST
it works because it creates the database called TEST under the instance of my SQL that the cmd had all the connection strings established.
So you are saying you execute your C# code it creates a database but it returns incorrect syntax near database, am i understanding that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.