Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql - Create Database & Table dynamically

This code is not working. Can anyone direct me where I can find examples of creating a Postgresql database and table on the fly with C#?

     const string connStr = "Server=localhost;Port=5432;
                          User Id=postgres;Password=enter;Database=postgres";

        var m_conn = new NpgsqlConnection(connStr);

        // creating a database in Postgresql
        m_createdb_cmd = new NpgsqlCommand("CREATE DATABASE IF NOT EXISTS  \"testDb\" " +
                                       "WITH OWNER = \"postgres\" " +
                                       "ENCODING = 'UTF8' " +
                                       "CONNECTION LIMIT = -1;", m_conn);

        // creating a table in Postgresql
        m_createtbl_cmd = new NpgsqlCommand(
            "CREATE TABLE MyTable(CompanyName VARCHAR(150))";

        m_conn.Open();
        m_createdb_cmd.ExecuteNonQuery();
        m_createtbl_cmd.Connection = m_conn;
        m_conn.Close();

The db is created but I get a silent fail on creating the table.

like image 761
Joe Grasso Avatar asked Jul 24 '13 15:07

Joe Grasso


People also ask

How do I create a database in PostgreSQL pgAdmin?

Start pgAdmin III and (in linux from Application > Programs > pgAdmin III and in Windows All Programs > PostgreSQL 9.1 > pgAdmin III) and reach "Databases" under your Server menu in right-hand side pane of your pgAdmin III window. Right click on "Databases" and click on "New Database...".

What is the command used for creating a database in PostgreSQL?

createdb creates a new PostgreSQL database. Normally, the database user who executes this command becomes the owner of the new database. However, a different owner can be specified via the -O option, if the executing user has appropriate privileges. createdb is a wrapper around the SQL command CREATE DATABASE .

Which are the methods PostgreSQL provides to create a new database?

PostgreSQL provides two methods for creating a new database: the CREATE DATABASE SQL command, and the createdb command-line executable.


Video Answer


3 Answers

I would do this:

string connStr = "Server=localhost;Port=5432;User Id=postgres;Password=enter;";
var m_conn = new NpgsqlConnection(connStr);
var m_createdb_cmd = new NpgsqlCommand(@"
    CREATE DATABASE IF NOT EXISTS testDb
    WITH OWNER = postgres
    ENCODING = 'UTF8'
    CONNECTION LIMIT = -1;
    ", m_conn);
m_conn.Open();
m_createdb_cmd.ExecuteNonQuery();
m_conn.Close();

connStr = "Server=localhost;Port=5432;User Id=postgres;Password=enter;Database=testDb";
m_conn = new NpgsqlConnection(connStr);
m_createtbl_cmd = new NpgsqlCommand(
   "CREATE TABLE table1(ID CHAR(256) CONSTRAINT id PRIMARY KEY, Title CHAR)"
   , m_conn);
m_conn.Open();
m_createtbl_cmd.ExecuteNonQuery();
m_conn.Close();

The use of var here is not recommended. I used it as I don't know what are the returned types but you should.

Notice the use of a raw string (@). It makes string building simple.

Do not use identifiers surrounded by double quotes in Postgresql unless the identifier is otherwise illegal. It will make you life much harder.

like image 59
Clodoaldo Neto Avatar answered Sep 24 '22 19:09

Clodoaldo Neto


seems like you simply forget to invoke ExecuteNonQuery method of m_createtbl_cmd:

m_createtbl_cmd.ExecuteNonQuery();

Also you can simplify it using DynORM library: http://dynorm.codeplex.com/

Hope it helps!

like image 26
rhyen brock Avatar answered Sep 27 '22 19:09

rhyen brock


You can pass the ConnectionString to this function :

  private static string GetConnectionString(string postgreSqlConnectionString)
        {
            NpgsqlConnectionStringBuilder connBuilder = new()
            {
                ConnectionString = postgreSqlConnectionString
            };

            string dbName = connBuilder.Database;

            var masterConnection = postgreSqlConnectionString.Replace(dbName, "postgres");

            using (NpgsqlConnection connection = new(masterConnection))
            {
                connection.Open();
                using var checkIfExistsCommand = new NpgsqlCommand($"SELECT 1 FROM pg_catalog.pg_database WHERE datname = '{dbName}'", connection);
                var result = checkIfExistsCommand.ExecuteScalar();

                if (result == null)
                {
                    using var command = new NpgsqlCommand($"CREATE DATABASE \"{dbName}\"", connection);
                    command.ExecuteNonQuery();
                }
            }

            postgreSqlConnectionString = masterConnection.Replace("postgres", dbName);

            return postgreSqlConnectionString;
        }

This will retrieve dbname from ConnectionString then checks if it already exists or not. if it didn't exist it will create one with the given dbname.

You should use above function in ConfigureServices of Startup class like this :

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyDbContext>(options =>
        {    
                options.UseNpgsql(GetConnectionString(Configuration["YourConnectionString"]));
        });
    }
like image 45
Kaveh Naseri Avatar answered Sep 26 '22 19:09

Kaveh Naseri