我有一个mysql表,我的c#程序包含类似登录/注册的东西。
我正在使用这种方法打开连接,关闭它以及更多东西: 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");
}
我只是将它用于新行但是我想如果“id”已经存在,只需增加他行的1个access(int)单元格。谢谢。
答案 0 :(得分:0)
您应该使用SQL Parameters。您可以通过以下查询实现目标:
string query =
"IF EXISTS (SELECT * FROM skinsdb WHERE id=@id)
UPDATE skinsdb SET acces=acces+1 WHERE id=@id
ELSE
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);
cmd.Parameters.AddWithValue("@id",id);
cmd.Parameters.AddWithValue("@ip",ip);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
答案 1 :(得分:0)
如果您在id上只有一个唯一索引,那么您可以使用
"INSERT INTO skinsdb (id, acces, ip) VALUES('" + id + "', 1 , '" + ip + "')
ON DUPLICATE KEY UPDATE acces=acces+1";