0

I'm trying to execute a query for MySql using while loop but it gives me error and I don't have any idea how to fix it. Without the loop, the code works well.

Additional information: Object reference not set to an instance of an object.

Here is what i got:

String copies = txtcopies.Text;
int x = Convert.ToInt32(copies);
int n = 0;

while (n < x)
{
    string loadstring = @"server=localhost;database=librarys;userid=root;password=1234;";

    MySqlConnection conDataBase = new MySqlConnection(loadstring);

    MySqlCommand cmdDataBase = new MySqlCommand("SELECT func_add_book('" + this.lblbnum.Text + "','" + this.txtisbn.Text + "','" + this.txttitle.Text + "','" + this.txtauthor.Text + "','" + this.txtpublisher.Text + "','" + this.txtdate.Text + "','" + this.txtcost.Text + "');", conDataBase);
    string returnedValue = cmdDataBase.ExecuteScalar().ToString();

    n++;

    conDataBase.Open();
    ClearAllText(txtcopies);
    MessageBox.Show(returnedValue);
}
4
  • 2
    Your error will tell you the exact line where it's happening. See stackoverflow.com/questions/4660142/… for some good tips on tracking down the error on that line. Commented Oct 19, 2015 at 1:02
  • Why are you opening the connection after you execute the command? Commented Oct 19, 2015 at 1:12
  • Why do you have to create a new connection at each loop? Commented Oct 19, 2015 at 1:15
  • You must open connection before execute after that I guess this line is the error... string returnedValue = cmdDataBase.ExecuteScalar().ToString();. Due to returning null and you try to .ToString() it Commented Oct 19, 2015 at 1:18

1 Answer 1

2

The problem is that you are opening your connection after executing the query. Also you only need to open SQL connection once in your code. Try the below code and see if it works.

String copies = txtcopies.Text;
int x = Convert.ToInt32(copies);
int n = 0;
string loadstring = @"server=localhost;database=librarys;userid=root;password=1234;";
MySqlConnection conDataBase = new MySqlConnection(loadstring);
try
{
    conDataBase.Open();
    while (n < x)
    {
        MySqlCommand cmdDataBase = new MySqlCommand("SELECT func_add_book('" + this.lblbnum.Text + "','" + this.txtisbn.Text + "','" + this.txttitle.Text + "','" + this.txtauthor.Text + "','" + this.txtpublisher.Text + "','" + this.txtdate.Text + "','" + this.txtcost.Text + "');", conDataBase);
        string returnedValue = cmdDataBase.ExecuteScalar().ToString();
        n++;
        ClearAllText(txtcopies);
        MessageBox.Show(returnedValue);
    }
}
Catch (Exception Ex)
{
}
Finally
{
    conDataBase.Close()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.