我想從我的DataBaseOptions類中的此方法訪問我的數據庫。我正在使用ASP.NET進行Web開發。SelectCommand.Connection未初始化
每當我運行此方法,在另一個類,我得到以下錯誤:
SelectCommand.Connection is not initialized
而且它說,錯誤是線40.這是我的代碼:
(將本着「 adapter.Fill(DT);」是40行
private string connectionString = "oop_string"; // Global Variable
private static SqlConnection mycon = new SqlConnection(); // Global Variable
private static SqlCommand mycmd = new SqlCommand(); // Global Variable
public void setupConnection() {
mycon.ConnectionString = ConfigurationManager.ConnectionStrings[connectionString].ToString();
mycmd.Connection = mycon;
}
public bool UserExists(string username, string password) {
setupConnection();
mycmd.CommandText = "SELECT user_id FROM users WHERE user_username = @username AND user_password = @password";
mycmd.Parameters.Add("@username", SqlDbType.VarChar).Value = username;
mycmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password;
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(mycmd);
adapter.Fill(dt);
if(dt.Rows.Count == 0) {
return false;
} else {
return true;
}
}
public int getUserID(string username, string password) {
setupConnection();
mycmd.CommandText = "SELECT user_id FROM users WHERE user_username = @username AND user_password = @password";
mycmd.Parameters.Add("@username", SqlDbType.VarChar).Value = username;
mycmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password;
SqlDataReader reader = mycmd.ExecuteReader();
if(reader.Read()) {
return Convert.ToInt32(reader["user_id"]);
}
mycon.Close();
return 0;
}
如果我試圖把一切從setupConnection();到UserExists()的開始;和getUserID();我得到以下錯誤:
ConnectionString property has not been initialized.
它現在聲稱該錯誤在第51行。「SqlDataReader reader = mycmd.ExecuteReader();」。
我的老師和我都嘗試了一切,谷歌,其他同學,老師。我們無法找到解決方案。
確保在setupConnection()方法中添加mycon.Open並添加以下行adapter.SelectCommand.Connection = mycon adapter.Fill(DT)之前;.希望它有幫助 – MMK 2013-04-24 08:06:25