adrasteia adrasteia - 3 months ago 9
MySQL Question

C# Mysql create new row but if exist don't

I have a mysql table and my c# program includes something simular like login/register.

I am using this methods for openning connection, close it and some more stuff :
http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL

public void Insert(string id,string ip)
{
string query = "INSERT INTO skinsdb (id, acces, ip) VALUES('" + id + "', 1 , '" + ip + "')";

//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);

//Execute command
cmd.ExecuteNonQuery();

//close connection
this.CloseConnection();
}
else MessageBox.Show("code 18");
}


I am simply using this for new row BUT i want if "id" already exist, just increase 1 acces(int) cell of his row. Thank you.

Answer

If you have just a single unique index on id then you can use

"INSERT INTO skinsdb (id, acces, ip) VALUES('" + id + "',  1 , '" + ip + "') 
ON DUPLICATE KEY UPDATE acces=acces+1";
Comments