0

i am making a system now, using C# winforms, and mysql database, and there is a part there that I want to check first if the id exist in the database, and if there is no record it will proceed to a certain procedure, but i am getting an error of Object not reference not set, how can I fix it? , thanks to those who will answer

Here is my sample code

string constring2 = "datasource='localhost';port='3306';username='root';password=1234";
string query2 = "select count(*) from betahms.billing where patient_id = '"+ textBox1.Text +"' ;";
MySqlConnection conDataBase2 = new MySqlConnection(constring2);
MySqlCommand cmdDataBase2 = new MySqlCommand(query2, conDataBase2);

int count = (int)cmdDataBase2.ExecuteScalar();

if (count > 0)
{
     //do something
}
Simon Karlsson
  • 4,090
  • 22
  • 39
  • 1
    And of course, don't use textbox value directly, sql injection. Use parameters instead. – Andy Wiesendanger Feb 22 '16 at 15:06
  • you also are not opening your `MySqlConnection` – Jonesopolis Feb 22 '16 at 15:06
  • As Soner Gönül points out, you can narrow it down by tracing your code to the line where the runtime exception occurs. – Simen S Feb 22 '16 at 15:07
  • thanks guys, it was a big help, thank you very much – TheDamnGuy Feb 22 '16 at 15:10
  • 1
    If you found the issue, and you think it's helpful to others, post it as answer. If not useful, delete question. – Andy Wiesendanger Feb 22 '16 at 15:22
  • `ExecuteScalar` [returns a null reference](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx) if there are no results from the query. Beyond that, it doesn't return the number of records if there is a match, it returns an **object** containing the first matched record. Really, reading at very least the "return value" part of the method's documentation entry about the easiest thing you can do to help yourself out... – J... Feb 22 '16 at 20:10

0 Answers0