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

时间:2014-04-03 11:58:28

标签: c# mysql asp.net

我想检查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..!!!");
            }
        }

    }

希望任何人都可以提供帮助。抱歉我的英文不好

2 个答案:

答案 0 :(得分:0)

你能试试吗

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();
}

答案 1 :(得分:0)

替换此行:

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

这一行:

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