简体   繁体   中英

MySql connection in C#

i was making a simple windows application form, to register some people in a database, so i made a connection class there is it:

public void Query_send(string cmd)
    {


        String config = "server=127.0.0.1;uid=root;database=bdcliente;";

        MySqlConnection conn = new MySqlConnection(config);
        MySqlCommand comm = new MySqlCommand(cmd, conn);
        try
        {
            conn = new MySql.Data.MySqlClient.MySqlConnection();
            conn.ConnectionString = config;
            conn.Open();
        }
        catch
        {
            MessageBox.Show("Error when connecting to the database!");
        }
        finally
        {
            conn.Close();
        }
    }

and then in the BUTTON to give the informations for the MySql i use this:

        private void button1_Click(object sender, EventArgs e)
    {
        Query instance = new Query();
        instance.Query_send("INSERT INTO `tbcliente`(`codCliente`, `name`, `cpf`, `telephone`) VALUES ([" + textBox1 + "],[" + textBox2 + "],[" + textBox3 + "],[" + textBox4 + "])");
    }

i always get the error with the connection when i click the register button, may someone help me or give me a link of a tutorial that teaches the correct way of doing this? Thanks, Iago.

My guess is that you need to wrap the VALUES clause results in single quotes as the SQL you are generating will be invalid.

VALUES ('" + textbox1 + "')

Brackets are only required when referring to table or column names. Not when you're referring to string literals.

Odd question, but have you tried applying a password to the database? Depending on the version of MySQL, I have had some issues with leaving the root password unassigned (on local machine you can be safe and just assign 'root' as the password as well). Another option would be to create a user account with permissions and try connection with those credentials.

Not sure if that will help, but it's process of elimination.

Also not sure if method was work in process, but even if it connected there was no execute command against the database.

public void Query_send(string cmd)
{


    String config = "server=localhost;uid=root;database=bdcliente;";
    MySqlConnection conn = new MySqlConnection(config);
    MySqlCommand comm = new MySqlCommand(cmd, conn);

    try
    {
        conn.Open();
        comm.ExecuteNonQuery(); '--this was missing
    }
    catch
    {
        MessageBox.Show("Error when connecting to the database!");
    }
    finally
    {
        conn.Close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM