kira.tk
kira.tk

Reputation: 13

How to set variables into a JDBC statement?

It works when i try to insert variables for example :

String insertStr="INSERT INTO  table1(username1,password1) VALUES(\"john\",\"password\")";

but unable to insert using variable

String a=username.getText();
String b=password.getText();

try {
    Class.forName("com.mysql.jdbc.Driver");  
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db1","root","");  

    Statement stmt=con.createStatement();        
    String insertStr="INSERT INTO  table1(username1,password1) VALUES(a,b);";
    stmt.executeUpdate(insertStr);
} catch (Exception e) { }

Upvotes: 1

Views: 6489

Answers (3)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59950

Use [PreparedStatement][1] instead of your way, because your way can be a victim of SQL Injection or Syntax errors :

String insertStr = "INSERT INTO  table1(username1,password1) VALUES(?, ?)";
try (PreparedStatement pst = con.prepareStatement(insertStr)) {
    pst.setString(1, a);
    pst.setString(2, b);
    pst.executeUpdate();
}

For reason of security I don't suggest to get password with getText(), instead use getPassword(), so you can use :

pst.setString(1, username.getText());
pst.setString(2, new String(passwordField.getPassword()));

Take a look at this :

Upvotes: 3

Tim Weber
Tim Weber

Reputation: 868

The most common way to insert variable values into sql is to use the PreparedStatement Object

With this object, you can add variable values into a SQL Query without fearing of SQL injection. Here an example of PreparedStatement :

//[Connection initialized before]
String insertStr="INSERT INTO  table1(username1,password1) VALUES(?,?);";
PreparedStatement myInsert = myConnectionVariable.prepareStatement(insertStr); // Your db will prepare this sql query
myInsert.setString(1, a); //depending on type you want to insert , you have to specify the position of your argument inserted (starting at 1)
myInsert.setString(2, b); // Here we set the 2nd '?' with your String b
myInsert.executeUpdate(); // It will returns the number of affected row (Works for UPDATE,INSERT,DELETE,etc...)
//You can use executeQuery() function of PreparedStatement for your SELECT queries

This is safer than using String concatenation like this : VALUES("+a+","+b+");

Take a look at Java Doc for more information ;)

Upvotes: 0

maio290
maio290

Reputation: 6732

Since you are inserting "a" and "b" as String, not their variable values.

String insertStr="INSERT INTO  table1(username1,password1) VALUES("+a+","+b+");"; 

should do it, but I would recommend to use a prepared statement here: https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

Upvotes: 0

Related Questions