數據庫的測試代碼以下 :java
一、新建表test,sql代碼以下:mysql
create table test( field1 int not null ) TYPE=MyISAM ; insert into test(field1) values(1);
二、刪除已存在的存儲過程,代碼以下:sql
delimiter // -- 定義結束符號 drop procedure p_test;
三、mysql存儲過程定義,代碼以下:數據庫
create procedure p_test() begin declare temp int; set temp = 0; update test set field1 = values(temp); end
四、 Java調用帶有輸入參數的存儲過程,代碼以下:
bash
public static void callIn(int in){ //獲取鏈接 Connection conn = ConnectDb.getConnection(); CallableStatement cs = null; try { //能夠直接傳入參數 //cs = conn.prepareCall("{call sp1(1)}"); //也能夠用問號代替 cs = conn.prepareCall("{call sp1(?)}"); //設置第一個輸入參數的值爲110 cs.setInt(1, in); cs.execute(); } catch (Exception e) { e.printStackTrace(); } finally { try { if(cs != null){ cs.close(); } if(conn != null){ conn.close(); } } catch (Exception ex) { ex.printStackTrace(); } } }
五、Java調用帶有輸出參數的存儲過程,代碼以下:工具
public static void callOut() { Connection conn = ConnectDb.getConnection(); CallableStatement cs = null; try { cs = conn.prepareCall("{call sp2(?)}"); //第一個參數的類型爲Int cs.registerOutParameter(1, Types.INTEGER); cs.execute(); //獲得第一個值 int i = cs.getInt(1); System.out.println(i); } catch (Exception e) { e.printStackTrace(); } finally { try { if(cs != null){ cs.close(); } if(conn != null){ conn.close(); } } catch (Exception ex) { ex.printStackTrace(); } } }
六、Java調用輸出結果集的存儲過程,代碼以下:測試
public static void callResult(){ Connection conn = ConnectDb.getConnection(); CallableStatement cs = null; ResultSet rs = null; try { cs = conn.prepareCall("{call sp6()}"); rs = cs.executeQuery(); //循環輸出結果 while(rs.next()){ System.out.println(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(rs != null){ rs.close(); } if(cs != null){ cs.close(); } if(conn != null){ conn.close(); } } catch (Exception ex) { ex.printStackTrace(); } } } }
七、Java獲取數據庫鏈接的工具類,代碼以下: url
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ConnectDb { public static Connection getConnection(){ Connection conn = null; PreparedStatement preparedstatement = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); String dbname = "test"; String url="jdbc:mysql://localhost/dbname?user=root&password=root&useUnicode=true&characterEncoding=utf-8"; conn= DriverManager.getConnection(url); } catch (Exception e) { e.printStackTrace(); } return conn; } }