I want to send data from my C# app to mysql.
The problem is that when I click the button nothing change in mysql.
Using this code:
private void updateUser()
{
string connectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=test;";
// Update the properties of the row with ID 1
string query = "UPDATE `users` SET `id` = 1, `meno`='Willy',`priezvisko`='Wonka',`email`='[email protected]' WHERE id = 1";
MySqlConnection databaseConnection = new MySqlConnection(connectionString);
MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
commandDatabase.CommandTimeout = 60;
MySqlDataReader reader;
try
{
databaseConnection.Open();
reader = commandDatabase.ExecuteReader();
// Succesfully updated
databaseConnection.Close();
}
catch (Exception ex)
{
// Ops, maybe the id doesn't exists ?
MessageBox.Show(ex.Message);
}
}
And the button to trigger it:
private void button_start_Click(object sender, EventArgs e)
{
updateUser();
}
CodePudding user response:
You are using ExecuteReader, which is intended to execute SELECT queries. Because this is an UPDATE query, you should use ExecuteNonQuery instead.
The difference here is that ExecuteReader might not actually be going to the database until you try to get some data back.
Sidenote - You've got this tagged as phpmyadmin, but I suspect you meant to use mysql instead. Phpmyadmin is a PHP-based interface for MySQL.
CodePudding user response:
The problem was the actual query I wanted to do.
I changed it to:
string updateQuery = "INSERT INTO users(meno, priezvisko, email) VALUES ('Rene', 'Martin', '[email protected]');";
intead of:
string query = "UPDATE `users` SET `id` = 1, `meno`='Willy',`priezvisko`='Wonka',`email`='[email protected]' WHERE id = 1";
It's caused by my improper knowledge.
