How To Use Java Variable To Insert Values To Mysql Table?
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
Solution 1:
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
:
PreparedStatementpstmt= 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();
Solution 2:
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Solution 3:
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry` (pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
Solution 4:
import java.sql.*;
classAdbs1{
publicstaticvoidmain(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","@dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Post a Comment for "How To Use Java Variable To Insert Values To Mysql Table?"