2015-10-19 104 views
0

我試圖使用while循環爲MySql執行查詢,但它給了我錯誤,我不知道如何解決它。沒有循環,代碼運行良好。嘗試使用while循環多次執行查詢

附加信息:未將對象引用設置爲對象的實例。

這裏是我的了:

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); 
} 
+2

你的錯誤會告訴你它發生的確切位置。請參閱http://stackoverflow.com/questions/4660142/what-is-a-ullreferenceexception-and-how-do-i-fix-it瞭解跟蹤該線路錯誤的一些好的提示。 – Jacob

+0

爲什麼在執行命令後打開連接? – Crowcoder

+0

爲什麼你必須在每個循環創建一個新的連接? – Muffun

回答

2

的問題是,您正在打開執行查詢後您的連接。 此外,您只需在代碼中打開一次SQL連接。嘗試下面的代碼,看看它是否工作。

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() 
}