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);
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With