Search code examples
c#npgsql

Connection property has not been initialized - Npgsql C#


I am trying to connect to my postgres database but im getting stuck with Connection property has not been initialized.

I am using a class for open connection

 class DBConnection
        {
            public static NpgsqlConnection conn = null;

            public void Connection_open()
            {
                string connstring = String.Format("Host=localhost;Database=Dokument_API;Username=postgres;Password=******");
                var conn = new NpgsqlConnection(connstring);
                conn.Open();
            }
            public void Connection_close()
            {
                conn.Close();
            }
        }

In form I have this code

private void button1_Click(object sender, EventArgs e)
        {
            //Open connection from class
            DBConnection NewConnection = new DBConnection();
            NewConnection.Connection_open();

            NpgsqlCommand cmd = new NpgsqlCommand("INSERT INTO anrop (exempelanrop,beskrivning,exempelsvar) VALUES ('" + exempelanrop_text.Text + "','" + beskrivning_text.Text + "','" + exempelsvar_text.Text + "')", DBConnection.conn);
            cmd.ExecuteNonQuery();
            MessageBox.Show("Uppgifter sparade");
        }

I get stuck on cmd.ExecuteNonQuery. Why??


Solution

  • your method defines a local var conn instead of asigning to the one you define on class level. Omit var:

     conn = new NpgsqlConnection(connstring);