我总是得到"对象引用未设置为对象的实例"。我不知道我做错了什么。我确实尝试执行查询:"从注册中选择count(*),其中Username =' Myname'它返回1;
代码:
protected void Button1_Click(object sender, EventArgs e)
{
DBConnect con = new DBConnect();
string query = "select count(*) from Registration where Username='" + TextBox1.Text + "'";
//Open connection
if (con.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, con.Initialize());
//Create a data reader and Execute the command
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp == 1)
{
string query1 = "Select Password from Registration where Username='" + TextBox1.Text + "'";
MySqlCommand pass = new MySqlCommand(query1, con.Initialize());
string password = pass.ExecuteScalar().ToString();
if (password == TextBox2.Text)
{
Session["new"] = TextBox1.Text;
Response.Redirect("GreenhouseHomepage.aspx");
}
else
{
Label1.Text = "Invalid Password...!!";
Label1.Visible = true;
}
}
else
{
Label1.Text = "Invalid Username...!!";
Label1.Visible = true;
}
}
//close Connection
con.CloseConnection();
}
错误:
答案 0 :(得分:0)
试一试。
//Open connection
if (con.OpenConnection() == true)
{
// Since you know that the connection is open, you can just
// pass the entire conn object
MySqlCommand cmd = new MySqlCommand(query, con);
//Create a data reader and Execute the command
int temp = Convert.ToInt32(cmd.ExecuteScalar());
如果没有找到记录,COUNT(*)
将返回0,因此您将始终从语法中获取值。