user1080390
user1080390

Reputation: 471

JDBC - How to insert a string value

When trying to insert the value of a string into my db using JDBC instead of inserting the String's value it inserts the String's name.

I have a string named firstName, the value of this string is given by user input.

Here is my sql statement:

String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','+firstName()','123')";

Upvotes: 2

Views: 17764

Answers (3)

Paul Vargas
Paul Vargas

Reputation: 42020

For various reasons, it is better to use java.sql.PreparedStatement. to execute statements with parameters. For example, if you want to avoid sql injection attacks.

See the examples in Using Prepared Statements from The Java Tutorials.

The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.

PreparedStatement pstmt = conn.prepareStatement(
   "UPDATE EMPLOYEES SET FIRST_NAME= ? WHERE ID = ?");

pstmt.setString(1, "user1080390"); // set parameter 1 (FIRST_NAME)
pstmt.setInt(2, 101); // set parameter 2 (ID)

int rows = pstmt.executeUpdate(); // "rows" save the affected rows

Upvotes: 6

Jeevi
Jeevi

Reputation: 3042

Something like this..

String firstName ="sample";
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124',"+firstName+",'123')";

Upvotes: 0

Karo
Karo

Reputation: 744

Try this

String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','"+firstName()+"','123')";

To prevent sql injections, you need to escape the string before using in a query or try the prepared statements.

Upvotes: 0

Related Questions