Home  >  Q&A  >  body text

mysql - C# always has this problem when connecting to the database int i = cmd.ExecuteNonQuery();

private void button1_Click(object sender, EventArgs e)

    {
        string MyConnectionString = "server=localhost;user=root;database=yangbo;port=3306;password=yangbo6510;";
        MySqlConnection connection = new MySqlConnection(MyConnectionString);
        if (textBox_username.Text.Trim() == "" && textBox_password.Text.Trim() == "")
        {
            MessageBox.Show("请输入用户名和密码进行注册");
        }
        else
        {
            connection.Open();//连接到数据库
            string sql = "select * from usernp where username='" + textBox_username.Text.Trim() + "' ;";
            MySqlCommand cmd = new MySqlCommand(sql, connection);
            cmd.CommandType = CommandType.Text;
            MySqlDataReader sdr;
            sdr = cmd.ExecuteReader();
            if (sdr.Read())
            {
                MessageBox.Show("用户名重复,请重新输入");
                textBox_username.Clear();
                textBox_password.Clear();
            }
            else
            {
                string sql1 = "insert into usernp (username,userpassword) values(' + textBox_username.Text.Trim() + ',' + textBox_password.Text.Trim() +')";
                cmd = new MySqlCommand(sql1, connection);
                int i = cmd.ExecuteNonQuery();
                if (i> 0)
                {
                    MessageBox.Show("注册成功");
                    textBox_username.Clear();
                    textBox_password.Clear();
                }
                
                else{
                    MessageBox.Show("注册不成功");
                    textBox_username.Clear();
                    textBox_password.Clear();
                }
            }
            connection.Close();
        }
    }
高洛峰高洛峰2711 days ago640

reply all(3)I'll reply

  • 黄舟

    黄舟2017-05-18 10:48:30

    Could you please tell me what the specific problem is? In addition, it seems that the single quotes in sql1 should be changed to double quotes, which is your original intention, but after changing it, you need to add the necessary wrapping single quotes.

    reply
    0
  • ringa_lee

    ringa_lee2017-05-18 10:48:30

    First of all, please do not splice sql, and secondly, use sqlparameter

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-18 10:48:30

    SQL splicing is wrong

    reply
    0
  • Cancelreply