Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use java variable to insert values to mysql table?

Tags:

java

sql

mysql

Hi i am trying to insert the values in to mysql table. i am trying this code. i have assigned values to variable and i want to pass that variable to that insert statement. Is this correct?

code
    int tspent = "1";
    String pid = "trng";
    String tid = "2.3.4";
    String rid = "tup";
    String des = " polish my shoes!";

    INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');

here is what i have tried, but i am not able to insert values

try
       {
           conn=DBMgr.openConnection();     
           String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
           st = conn.createStatement();
           rs = st.executeQuery(sqlQuery); 
       }
like image 219
milano Avatar asked Jun 20 '13 06:06

milano


1 Answers

You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.

You should use PreparedStatement:

PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\

Then set the variables at those index:

pstmt.setString(1, pid);
// Similarly for the remaining 4 

// And then do an executeUpdate
pstmt.executeUpdate();
like image 145
Rohit Jain Avatar answered Oct 31 '22 22:10

Rohit Jain