Reputation: 23
Since it seems that I try to learn how to work with SQL and Java the hard way my Question is:
Is it possible to use a variable IN BETWEEN Quotation marks?
I know that if you use the output you can work like this:
System.out.println(_name + " "+_points+ " "+_ID);
Is there a way to make it all in only one Quotation Mark pair? Something like this:
System.out.println("_name _points _ID");
If yes, how do I mark them so that the Compiler knows that it is a Variable that he should print?
The reason why I want to know it is simple, I try to use executeUpdate
stmt.executeUpdate("INSERT INTO usertable VALUES("+_name+")");
and want it without the addition signs in there.
Upvotes: 2
Views: 2458
Reputation: 2759
No you cannot use a variable inside a String literal. There are a couple of options though.
The first is the way you are currently doing it using concatenation with the + sign:
String query = "INSERT INTO table VALUES(" + name + ")";
Another way is to use String.format
String query = String.format("INSERT INTO table VALUES(%s)", name);
But the preferred method for SQL to avoid SQL Injection attacks is using a PreparedStatement:
String query = "INSERT INTO table VALUES(?)";
PreparedStatement statement = con.prepareStatement(query);
statement.setString(1, name);
statement.executeUpdate();
Upvotes: 2
Reputation: 358
You can use preparedStatement:
Example :
query :
private static String SQL_INSERT_NEW_RULE = "INSERT INTO Table (A, B) VALUES (?, ?)";
then you can put them like this:
PreparedStatement pStmt=null;
pStmt = conn.prepareStatement(SQL_INSERT_NEW_RULE);
int index = 1;
pStmt.setString(index++, "value for A");
pStmt.setLong(index++, "Value for B");
Upvotes: 0
Reputation: 23381
If you have a variable and want to pass it to your query statement with the quotation just add the quotes to your command. If the quotes are single quotes you don't need to scape then but if it is, you gona need to:
stmt.executeUpdate("INSERT INTO usertable VALUES('"+_name+"')");
^
|_Just add the quotes inside the
string
If it is a double quote (which I think is hardly the case) you need to scape then. Scaping is a way to tell the compiler that that specific string is special
stmt.executeUpdate("INSERT INTO usertable VALUES(\""+_name+"\")");
^
|_See the slash before the double quote?
But since you are learning you should learn the proper way to do it, because use variables with quotations will make your code prone to SQL Injection
So The better way to do it is to use Prepared Statements and language willl take care of the quotes for you. It would be:
String sql = "INSERT INTO usertable VALUES (?)"
preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setString(1, "name you want");
See here a complete example: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/
Upvotes: 0