所以我试着写一个方法来检查用户输入的用户名是否存在于MySQL数据库中。但是我遇到了这个例外:
System.NullReferenceException: Object reference not set to an instance of an object.
指向这行代码:
cmd.Parameters.AddWithValue("?username", usernameTextBox.Text);
以下是checkusername方法:
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySqlConnection(connString);
conn.Open();
queryStr = "";
queryStr = "SELECT count(*) FROM webappdemo.userregistration WHERE username = ?username";
cmd.Parameters.AddWithValue("?username", usernameTextBox.Text);
cmd = new MySqlCommand(queryStr, conn);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if (result > 0)
{
//username taken
doesuserexist = true;
LabelUsername.Text = "Username Exists";
}
else
{
//username good
doesuserexist = false;
LabelUsername.Text = "";
}