9

How to create a database using connector/net programming? How come the following doesn't work?

    string connStr = "server=localhost;user=root;port=3306;password=mysql;";
    MySqlConnection conn = new MySqlConnection(connStr);
    MySqlCommand cmd;
    string s0;

    try
    {
        conn.Open();
        s0 = "CREATE DATABASE IF NOT EXISTS `hello`;";
        cmd = new MySqlCommand(s0, conn);
        conn.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

4 Answers 4

18

You need to execute the command and also make sure to properly dispose objects:

string connStr = "server=localhost;user=root;port=3306;password=mysql;";
using (var conn = new MySqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "CREATE DATABASE IF NOT EXISTS `hello`;";
    cmd.ExecuteNonQuery();
}
Sign up to request clarification or add additional context in comments.

1 Comment

will this work in VS 2013 or do you have to attach a few Dll first?
16

You might want to execute the MySqlCommand. Now you just create one, but it doesn't execute your query.

Try this:

conn.Open();
s0 = "CREATE DATABASE IF NOT EXISTS `hello`;";
cmd = new MySqlCommand(s0, conn);
cmd.ExecuteNonQuery();
conn.Close();

2 Comments

will this work in VS 2013 or do you have to attach a few Dll first?
I tried this in my c# program but did not work. You must use ` rather than ' around the database name. Thanks
1

execute your command and try this function

public void createDatabase(string server, string port, string database, string username, string password)
    {
        string connectionstring = string.Format("Server = {0}; Port ={1}; Uid = {2}; Pwd = {3}; pooling = true; Allow Zero Datetime = False; Min Pool Size = 0; Max Pool Size = 200; ", server, port, username, password);
        using (var con = new MySqlConnection { ConnectionString = connectionstring })
        {
            using (var command = new MySqlCommand { Connection = con })
            {
                if (con.State == ConnectionState.Open)
                    con.Close();

                try
                {
                    con.Open();
                }
                catch (MySqlException ex)
                {
                    msgErr(ex.Message + " connection error.");
                    return;
                }

                try
                {
                    command.CommandText = @"CREATE DATABASE IF NOT EXISTS @database";
                    command.Parameters.AddWithValue("@database", database);
                    command.ExecuteNonQuery();//Execute your command
                }
                catch (MySqlException ex)
                {
                    msgErr(ex.Message + " sql query error.");
                    return;
                }
            }
        }

    }

Comments

-1
Imports MySql.Data.MySqlClient
Public Class Form1
    Private dBf As String = "Empresa"
    Private str As String = "Server = localhost; uid=root; pwd=;Database=mysql; pooling=false;"
    Private Cmd As MySqlCommand
    Private Con As New MySqlConnection(str)
    Private Sub Form1_Load() Handles MyBase.Load
        Try
            Con.Open()
            Cmd = New MySqlCommand("Create Database If Not exists " + dBf, Con)
            Cmd.ExecuteNonQuery() : Con.ChangeDatabase(dBf)
            Cmd = Con.CreateCommand
            Cmd.CommandText = "CREATE TABLE Empleado" &
             "(Id Char(10)  COLLATE utf8_spanish_ci Not Null," &
             "name  VarChar(50)  COLLATE utf8_spanish_ci Not Null," &
             "email VarChar(50)   COLLATE utf8_spanish_ci Not Null," &
             "website VarChar(50)  COLLATE utf8_spanish_ci Not Null," &
             "Primary Key(id)) ENGINE=MyISAM"
            Cmd.ExecuteNonQuery()
            MsgBox("Registros, ok!!!") : Con.Close()
        Catch ex As Exception
            MsgBox(Err.Description)
        End Try
    End Sub
End Class

1 Comment

There is no formatting. It does not help at all to solve the problem. Please remove or improve your answer thanks.

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.