Java 将列名作为整数过帐
我有游戏ID、hometeamid、visitorteamid和winnerid都是int 询问Java 将列名作为整数过帐,java,mysql,jdbc,prepared-statement,Java,Mysql,Jdbc,Prepared Statement,我有游戏ID、hometeamid、visitorteamid和winnerid都是int 询问 Update game set winnerid=hometeamid where gameid=1; 在Mysql工作台上运行良好 我试图从一个准备好的语句运行相同的语句,但没有成功抛出错误 java.sql.BatchUpdateException: Incorrect integer value: 'hometeamid' for column 'winnerId' at row 1 因
Update game set winnerid=hometeamid where gameid=1;
在Mysql工作台上运行良好
我试图从一个准备好的语句运行相同的语句,但没有成功抛出错误
java.sql.BatchUpdateException: Incorrect integer value: 'hometeamid' for column 'winnerId' at row 1
因为“hometeamid”是作为字符串传递的。
代码如下
String query = "update `match` set winnerid= ? where gameid=?";
Map<Integer, String> data = getMap();//gameid and either 'hometeamid' or 'awaytemid'
try {
PreparedStatement ps = connection.prepareStatement(query);
for (Map.Entry<Integer, String> entry : data.entrySet()) {
ps.setObject(1, entry.getValue());
ps.setInt(2, entry.getKey());
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException e) {
logger.error(e, e);
} finally {
closeQuietly(connection);
}
String query=“update`match`set winnerid=?where gameid=?”;
Map data=getMap()//gameid和“hometeamid”或“awaytemid”
试一试{
PreparedStatement ps=connection.prepareStatement(查询);
for(Map.Entry:data.entrySet()){
ps.setObject(1,entry.getValue());
ps.setInt(2,entry.getKey());
ps.addBatch();
}
ps.executeBatch();
}捕获(SQLE异常){
记录器错误(e,e);
}最后{
关闭(连接);
}
如何从PreparedStatement正确运行更新
非常感谢您的任何其他改进建议。请将您的查询更改为:
String query = "update `match` set winnerid = case when ? = 'hometeamid' then hometeamid else visitorteamid end where gameid=?"
不能在准备好的语句中将列名作为参数传递。只能传递值
如果确实需要此列名是动态的,则必须使用字符串连接来构建查询的这一部分。
entry.getValue()
可能返回“hometeamid”
(字符串
)它不是一个整数。是的,但我需要它作为一个无引号的字符串,因为它是一个列名。我用你的番石榴果酱,喜欢它。