JDBC - How to insert a string value
14,386
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
Author by
user1080390
Updated on June 14, 2022Comments
-
user1080390 almost 2 years
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')";
-
user1080390 almost 12 yearsI'll be sure to read up on PreparedStatement's in the coming weeks. Unfortunately , and I know this sounds bad; I haven't the time right at this moment, I have to meet a deadline for tommorow. Is there any chance you could be more specific?
-
leonbloy almost 12 yearsThis is the dirty and dangerous way, error prone (what if firstName contains quotes?), and, above all, has the danger of SQL injection attacks. Never do this in real code.
-
user1080390 almost 12 yearsProvider.java:90: cannot find symbol symbol : method firstName() localtion: class Provider String sql = "Insert INTO users (ID, firstName, address) Values ('124','"+firstName()+"','123')"; ^
-
Jonathan almost 12 yearsThe time you spend trying out dirty hacks could be spent reading up PreparedStatments and using it. Paul's code snippet should be enough to get you going.
-
user1080390 almost 12 yearsI tried to modify the prepared insert statement from this thread: stackoverflow.com/questions/1073101/… But I received the error: Cannot find symbol preparedstatement ...
-
Paul Vargas almost 12 yearsBe sure to properly import the necessary classes. Perhaps
import java.sql.*;
might suffice.