不会使用 executeScalar() 检查用户是否存在

本文关键字:检查 用户 是否 存在 executeScalar | 更新日期: 2023-09-27 17:56:19

我想检查我的MySQL数据库中是否已经存在用户。 我确实在数据库中插入了一个用户,并想检查该用户是否存在。当用户在文本框中插入某些内容时,我希望它验证用户名。我也尝试了:OnTextChanged="TextBoxUN_TextChanged"并将代码复制到TextBoxUN_TextChanged内。

这是我到目前为止的代码。

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) {
           string server = "wisteria.arvixe.com";
           string database = "greenhouse";
           string uid = "******";
           string password = "******";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
            MySqlConnection connection = new MySqlConnection(connectionString);
            connection.Open();
            string cmd = "SELECT COUNT(*) FROM registration WHERE Username='" + TextBoxUN.Text + "'";
            MySqlCommand userExist = new  MySqlCommand(cmd, connection);
            int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());               
            connection.Close();
            if (temp == 1)
            {
                Response.Write("User already exist..!!!");
            }
        }
    }

希望有人能帮忙。对不起,我的英语不好

不会使用 executeScalar() 检查用户是否存在

替换此行:

int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());

用这一行:

int temp = (Int32)cmd.ExecuteScalar();

你能试试这个吗

if (!IsPostBack)
{
    string server = "wisteria.arvixe.com";
    string database = "greenhouse";
    string uid = "******";
    string password = "******";
    string connectionString;
    connectionString = "SERVER=" + server + ";" + "DATABASE=" +
    database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
        MySqlConnection connection = new MySqlConnection(connectionString);
        connection.Open();
        string cmd = "SELECT COUNT(*) FROM registration WHERE Username='" + TextBoxUN.Text + "'";
        MySqlCommand userExist = new  MySqlCommand(cmd, connection);
        object obj = userExist.ExecuteScalar();
        int temp = -1;
        if (obj != DBNull.Value)
        {
           temp = Convert.ToInt32(obj);  
        }             
        if (temp == 1)
        {
            Response.Write("User already exist..!!!");
        }
        connection.Close();
}