嗨,我想将值插入到mysql表中.我正在尝试这段代码.我已将值赋给变量,我想将该变量传递给该insert语句.它是否正确?
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+"');
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的,但我无法插入值
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);
}
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 15
executeUpdate()只要查询是SQL数据操作语言语句,就应该使用方法.此外,您当前的查询易受SQL注入攻击.
你应该使用PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Run Code Online (Sandbox Code Playgroud)
然后在这些索引处设置变量:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Run Code Online (Sandbox Code Playgroud)
Gan*_*jan 14
试试这个,
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+"')");
Run Code Online (Sandbox Code Playgroud)
使用PreparedStatement并使用其setXXX()方法设置值。
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59269 次 |
| 最近记录: |