I'm trying to access my database, from this method in my DataBaseOptions class. I'm using this with ASP.NET for web development.
Whenever I run this method, In another class, I get following error:
SelectCommand.Connection is not initialized
And it says that the error is on line 40. Here's my code:
(The line with "adapter.Fill(dt);" is line 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;
}
If i try to put everything from setupConnection(); to the start of UserExists(); and getUserID(); I get the following error:
ConnectionString property has not been initialized.
Which it now claims, that the error is on line 51. The "SqlDataReader reader = mycmd.ExecuteReader();".
My teacher and I, have tried everything, google, other classmates, teachers. We can't seen to find a solution.