2

I am trying to connect a PostgreSQL database to a C# console app. This is my code:

static void Main(string[] args)
{
    string connstring = String.Format("Server=localhost;Port=5432;" +
                    "User Id=postgres;Password=admin;Database=mydb;");
    NpgsqlConnection conn = new NpgsqlConnection(connstring);
    conn.Open();

    string sql = string.Format("CREATE TABLE public.stvari2 ime text, broj smallint, id integer)");
    NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
    cmd.ExecuteNonQuery();
}

I literally copied the the reverse-engineered SQL query from Postgres, so I doubt that that's the problem. Anyhow, when I run it I get an exception:

An unhandled exception of type 'Npgsql.PostgresException' occurred in Npgsql.dll

at the last line (executeNonQuery). Any ideas?

2 Answers 2

3

Looking at your SQL string -- are you missing a ( ?

string sql = string.Format("CREATE TABLE public.stvari2 ime text, broj smallint, id integer)");

In here dont you need another ( --> public.stvari2( ime

string sql = string.Format("CREATE TABLE public.stvari2( ime text, broj smallint, id integer)");
Sign up to request clarification or add additional context in comments.

Comments

0

try like this it will work

 static void Main(string[] args)
        {

            String connections = "Server=192.168.1.163;Port=5432;Database=postgres;User Id=postgres;Password=root;";
            NpgsqlConnection connection = new NpgsqlConnection();
            connection.ConnectionString = connections;
            connection.Open();

            try
            {
                NpgsqlCommand cmd = new NpgsqlCommand();
                cmd.Connection = connection;
                cmd.CommandText = "INSERT INTO sector(name,address,designition,description,auto_id) values ('vinoth','chennai','sds','wdewd','123')";
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();                                                        
                cmd.Dispose();

            }
            catch (Exception e)
            {
                e.ToString();
            }
}

Comments

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.