jdbc呼叫儲存過程

不設限發表於2011-12-11

儲存過程:

CREATE PROCEDURE `mypro`(in mark varchar(20))
    NOT DETERMINISTIC
    SQL SECURITY DEFINER
    COMMENT ''
begin
if mark='teacher' then
select * from `teacher` order by id asc;
else
select * from `student` order by id desc;
end if;
end;


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;


public class TestProcedure {
public static void main(String[] args) throws Exception {
TestProcedure tp=new TestProcedure();
Connection conn=tp.getConn();
CallableStatement cs=conn.prepareCall("{call mypro(?)}");
cs.setString(1, "aaa");
ResultSet rs=cs.executeQuery();
tp.show(rs);
}

public Connection getConn() {
Connection conn=null;
String url="jdbc:mysql://localhost/dandan?user=root&password=dada";
try {
Class.forName("org.gjt.mm.mysql.Driver");
try {
conn=DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}

//列印結果集
public static void show(ResultSet rs) {
try {
while(rs.next()) {
System.out.println("Row: "+rs.getRow()+"\tId: "+rs.getInt(1)+"\tName: "+rs.getString(2)
+"\tSex: "+rs.getString(3)+"\tGrade: "+rs.getString(4));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

相關文章