[英]Java and prepareStatement with MySQL
我使用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?
謝謝!
在我看來,這有點像一個mysql存儲過程? 如果我沒記錯的話,應該直接在mysql中注冊。 這樣,您就可以使用准備好的語句來調用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.