使用android studio(3.5) 呼叫 mySQL stored procedures時出現錯誤(若僅執行單行可正常使用,但多行無法一次執行):
以下為文件內容:
Android studio main_activity.java(部分)
@Override
protected String doInBackground(String... strings) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user, pass);
String result ="";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("call login(@fname, '"+account+"', '"+password+"'); select @fname;");
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()){
result += rs.getString("fname").toString()+"您好!";
}
res = result;
}catch (Exception e){
e.printStackTrace();
res = e.toString();
}
return res;
}
mySQL stored procedures:
CREATE DEFINER=`currency`@`%` PROCEDURE `login`(out fname varchar(5), in acc varchar(100), in pwd varchar(50))
BEGIN
Declare exist int;
select count(*) into exist from client where account = acc and code = pwd;
if exist = 0 then
set fname = '遊客';
else
select f_name into fname from client where account = acc and code = pwd;
End IF;
END
補充:
目前已經用以下方法暫時繞過問題了,但各位大大要是有更好的方法也歡迎留言喔!:
CallableStatement cstmt = con.prepareCall("{call login(?,?,?)}");
cstmt.registerOutParameter(1, Types.VARCHAR);
cstmt.setString(2, account);
cstmt.setString(3, password);
cstmt.executeUpdate();
一般建議Android跟IOS不要直接操作資料庫.
比較有安全上的顧慮.
錯誤訊息是SQL 語法錯誤
你檢查看看
ResultSet rs = st.executeQuery("call login(@fname, '"+account+"', '"+password+"'); select @fname;");
實際上執行是
call login('@fname值', 'account值', 'password值');
select @fname;
1.以上SQL敍述語法是否正確?(可以貼在 SQL GUI 試試看)
2.會回傳你預期的 resultset 嗎?
選我正解