Nel

Nel

  • NA
  • 716
  • 1.1m

Problem with inserting into sql database

Aug 5 2011 3:51 AM
Hello,

I have a code for inserting data in database, which checks whether a row is inserted or not and returns th id of the row. Here is the code:

public bool vnesiDokument(Dokument dokument)
        {
            bool result = false;
            SqlConnection connection = null;
           
            try
            {
                // Open a database connection.
                connection = GetConnection();

                connection.Open();   //in this row I got error
 "Object reference not set to an instance of an object."

                // Create a command.
                SqlCommand command = new SqlCommand("vnesiDok", connection);
                command.CommandType = CommandType.StoredProcedure;
               
                // Add parameters to command.
                command.Parameters.AddWithValue("@vp", dokument.vp);
                command.Parameters.AddWithValue("@valuta", dokument.valuta);
                command.Parameters.AddWithValue("@valutakurs", dokument.valuta_kurs);
                command.Parameters.AddWithValue("@imeprez", dokument.imeprezime);
                command.Parameters.AddWithValue("@iznos", dokument.iznos);
                command.Parameters.AddWithValue("@iznosden", dokument.iznosden);
                command.Parameters.AddWithValue("@br_kas_izvod", dokument.br_kas_izvod);
                command.Parameters.AddWithValue("@br_smetka", dokument.br_pat_smetka);
                command.Parameters.AddWithValue("@tip", dokument.tip);
                command.Parameters.AddWithValue("@datum", dokument.datum);

                SqlParameter brdokParam = new SqlParameter(
                   "@brdok", SqlDbType.Int);
                brdokParam.Direction = ParameterDirection.Output;
                command.Parameters.Add(brdokParam);

                // Execute the command.
                int rowsAffected = command.ExecuteNonQuery();
                if (rowsAffected == 1)
                {
                    // Get the patient ID generated by the database for
                    // the new patient.
                    dokument.brdok = (int)command.Parameters["@brdok"].Value;
                    result = true;
                }
            }
            finally
            {
                // Close the database connection.
                if (connection != null)
                {
                    connection.Close();
                }
            }
            return result;
        }

Can anybody help me what's wrong with my code please?

Thanks


Answers (6)