Reputation: 31
I am working on a little project. Now I don't know, how to "replace" a old value in the mysql table. Here you can see the table:
Thats my methods:
MySQL.update("INSERT INTO OnlineServer (Name) VALUES ('" + API.getServerFreeServer() + "');");
public static void update(String qry) {
try {
java.sql.Statement st = con.createStatement();
st.executeUpdate(qry);
st.close();
} catch (SQLException e) {
connect();
e.printStackTrace();
}
}
The problem now is, if I update the mysql, it dont replace the value in the column "Name". It just add a new Value under the old Value. The table is Going to be too huge if I Update every 5 seconds.
I need exactly one value in the column "Name". So I have tryed to replace the insert but it doesn't work for me.
Maybe you have some ideas? Sorry for my bad English, I'am German.
Upvotes: 2
Views: 68
Reputation: 77876
INSERT
operation is for adding new record only and thus irrespective of you specify single column or 1million column it will add a new record. You actually need an UPDATE
statement saying
UPDTE OnlineServer SET Name = <value>
You might also want to check INSERT ... ON DUPLICATE KEY UPDATE
Upvotes: 0
Reputation: 521249
It sounds like you want to do an update here of the table, rather than an insert:
String sql = "UPDATE OnlineServer Set Name = ?";
PreparedStatement ps = dbConnection.prepareStatement(sql);
ps.setString(1, API.getServerFreeServer());
ps.executeUpdate();
By the way, your current query is doing raw string concatenation, making it prone to typos as well as SQL injection. I have used a prepared statement above, which is the most desirable way to execute a query using JDBC.
Upvotes: 1