-1

I'm using ADO.NET 2.0 driver from Embracadero and trying to connect to remote Interbase base (http://cc.embarcadero.com/item/25497). I'm trying to do insert query to my database, but when I do insert query it throws "Object reference not set to an instance of an object." Does anybody have the same problem?

I have:

    public DbConnection GetConnection()
    {
        DbConnection con = new TAdoDbxConnection();
        con.ConnectionString = _connectionString;

        return con;
    }

and then I do:

        using (var conn = GetConnection())
        {
            using (var cmd = conn.CreateCommand())
            { 
                cmd.CommandText = query;

                var param = cmd.CreateParameter();// <---- here exception is thrown
                NazwaChannel.ParameterName = "@param";
                NazwaChannel.Value = 1000;
                NazwaChannel.DbType = DbType.Int32;

                cmd.Parameters.Add(param);

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();

            }
        }

query is like "Insert into Table (tableID, columnname) values (GEN_ID(GenaratorName, 1), @param)".

Ant
  • 129
  • 1
  • 11
  • 1
    Well first of all, we need some code to be able to help you. Also, if you have a nullpointerexception, read [this](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it). –  Dec 27 '16 at 08:28
  • Just one suggestion. Grab the value of the query variable and try to insert in the DB directly to see if the problem is in the query. Otherwise I don't see anything wrong with your code. – st_stefanov Dec 27 '16 at 08:48
  • Bas, it's not nullpointexception – Ant Dec 27 '16 at 08:53
  • And one more suggestion - try to open the connection for test just before the cmd.CreateParameter(); and see if you get the same or similar error on the conn.Open() line. Then we will know that it is related to establishing the connection with the remote DB. – st_stefanov Dec 27 '16 at 08:53
  • When I do query like "Insert into tablename(id, param) values (uniqueId, 1)" everething is ok – Ant Dec 27 '16 at 10:09
  • finally, it could be solved by adding conn.Open() before using cmd.CreateCommand() xD But now it throws exception unknown token "@". – Ant Dec 27 '16 at 10:48
  • Were you able to get hold of the auto generated ID value ? – Shivanka May 07 '17 at 13:51

1 Answers1

1

The answer is:

  • using conn.Open() before parameter creation
  • instead of 'INSERT INTO TABLENAME (column1, column2, ...) VALUES (@value1, @value2, ...)' use 'INSERT INTO TABLENAME (column1, column2, ...) VALUES (? , ?, ...)'.
Ant
  • 129
  • 1
  • 11