我使用Java来做一些SQL查询。
一般来说,我想要执行的查询是:
set @uid=?; set @friendsList=?; IF EXISTS(select 1 from fb_user_friends join fb_user on " +
" fb_user.id = fb_user_friends.fb_user_id where uid=@uid) then " +
"update fb_user_friends set friends = @friendsList; ELSE insert " +
"into fb_user_friends(fb_user_id,friends) values(@uid,@friendsList); END IF;
我使用以下方式获取MySQL连接:
Class.forName("com.mysql.jdbc.Driver").newInstance();
this._sqlconn = DriverManager.getConnection(this._url,this._userName,this._password);
我尝试执行以下代码:
String sql="set @uid=?; set @friendsList=?; IF EXISTS(select 1 from fb_user_friends join fb_user on " +
" fb_user.id = fb_user_friends.fb_user_id where uid=@uid) then " +
"update fb_user_friends set friends = @friendsList; ELSE insert " +
"into fb_user_friends(fb_user_id,friends) values(@uid,@friendsList); END IF;";
try {
PreparedStatement stmt = this._sqlconn.prepareStatement(sql);
stmt.setLong(1,uid);
stmt.setString(2,StringUtils.join(friendsList.toArray(), ','));
stmt.executeUpdate();
}catch (SQLException e) ....
我得到例外:
class com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'set @friendsList='110633,2018837,6813007,8803501,10711399,500061635,500214841,50'
我不能用prepareStatement运行几个命令吗?
我是否需要找到一种不同的方法来设置MySQL变量uid和friendsList?
谢谢!
答案 0 :(得分:1)
这看起来有点像我的mysql存储过程?如果我没弄错的话,你应该直接在mysql中注册。这样,您就可以使用准备好的声明来调用它。