您好,我正在尝试将值插入到 mysql 表中。我正在尝试这段代码。 我已经为变量赋值,我想将该变量传递给该插入语句。 这是正确的吗?
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+"');
这是我试过的,但我无法插入值
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);
}
最佳答案
只要您的查询是SQL 数据操作语言 语句,您就应该使用executeUpdate()
方法。此外,您当前的查询容易受到 SQL Injection 的攻击.
你应该使用PreparedStatement
:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
然后在这些索引处设置变量:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
关于java - 如何使用java变量向mysql表中插入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17207088/