Atanas Pashkov
Atanas Pashkov

Reputation: 25

Query won't run from npgsql, but runs on postgresql pgAdmin

I have a problem running a simple insert query from my C# app towards a Postrges DB.

This is the function that builds the query:

string push = "INSERT INTO \"Tasks\"( \"TName\", \"Desc\", \"TType\", \"DCreated\", \"DEnd\") VALUES (\'" + this.Name + "\',\'" + this.Descr + "\'," + this.Type + ",\'" + this.StartDate + "\', \'" + this.EndDate + "\');";
                GenericDbClass.ExecutePush(push);

And this is the string that gets passed to the DB:

INSERT INTO "Tasks"( "TName", "Desc", "TType", "DCreated", "DEnd") VALUES ('dddddd','dddddddddddd',3,'13.04.2015 17:00', '24.04.2015 16:42');

If I copy the string and run it inside pgAdmin it works right of the bat, but from here it doesn't do anything - no exceptions thrown,no errors, nothing in the logs, as if it just doesn't reach the server.

In addition here is the push method:

public static void ExecutePush(string sql)
    {
        try
        {
            NpgsqlConnection conn = new NpgsqlConnection(GenericDbClass.GetDbConnString());
            conn.Open();
            NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
            conn.Close();
        }

        catch (Exception msg)
        {
            MessageBox.Show(msg.ToString());
            throw;
        }
    }

Edit: This is the working solution I found

public static void ExecutePush(string sql)
    {
        try
        {
            NpgsqlConnection conn = new NpgsqlConnection(GenericDbClass.GetDbConnString());
            conn.Open();
            NpgsqlCommand nc = new NpgsqlCommand(sql, conn);
            nc.ExecuteNonQuery();
            conn.Close();
        }

        catch (Exception msg)
        {
            MessageBox.Show(msg.ToString());
            throw;
        }
    }

Upvotes: 1

Views: 842

Answers (1)

Jon Hanna
Jon Hanna

Reputation: 113382

NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);

Means "Please create a data-adaptor that uses the INSERT SQL passed as sql to do a selection". That doesn't make much sense, and then you don't do anything with it, anyway.

conn.CreateCommand(sql).ExecuteNonQuery();

Seems more like what you want.

Upvotes: 2

Related Questions