user3331023 user3331023 - 5 months ago 7x
SQL Question

Save two values as one in a database (SQL)

I want to save two values as one in a database how can I do that?

Here's my code:

String v = "Voila";
String c = "Magic";
String url = "jdbc:mysql://localhost:3306/lemon";
Connection conn = DriverManager.getConnection(url,"r","s");
Statement st = conn.createStatement();
st.executeUpdate("INSERT INTO rtype set RType = '" + v + "'"); // how can I add 'c' in the same column?

catch (Exception e) {
System.err.println("Got an exception! ");
JOptionPane.showMessageDialog(null,"Please enter some values");

As you can see, I have two strings that I should combine as one then save in a database.

The column should have "Voila Magic" if successful.


Just concatenate them at the Java level before the insert:

st.executeUpdate("INSERT INTO rtype set RType = '" + v + " " + c + "'");
// Here ----------------------------------------------^^^^^^^^^^

If either v or c comes from an end user, beware that your code is wide open to SQL injection attacks; here's a humorous, but serious, illustration of them:

enter image description here

Even if they don't, if either could contain ', your statement would end up being invalid SQL and failing. Use PreparedStatement and parameter placeholders instead:

PreparedStatement ps = conn.prepareStatement("INSERT INTO rtype set RType = ?");
ps.setString(1, v + " " + c);