1:建立數據庫Studentjava
共兩個字段 id和snamemysql
主鍵Id ,自動遞增sql
sname ,字符類型varchar數據庫
2:打開navicateclipse
3:在BEGIN ,END中輸入:url
declare n bigint; set n = 201121029684; while n <= 201121029694 do insert into student(sname) values(n); set n = n + 1; end while;
以下圖code
保存名字爲rrr的儲存ip
4:myeclipse中新建一個Java工程get
如testio
5:新建類 GetConnection
添加代碼:
import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class GetConnection { public Connection getConnection() { Connection conn=null; try { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException ex) { System.out.println("加載驅動程序有錯誤"); } String url = "jdbc:mysql://localhost:3306/test?user=root&password=&useUnicode=true&characterEncoding=gb2312"; conn = DriverManager.getConnection(url); System.out.println("成功鏈接數據庫!!"); } catch (SQLException ex1) { System.out.print("取得鏈接的時候有錯誤,請覈對用戶名和密碼"); } return conn; } public static void main(String[]args) { GetConnection getConn=new GetConnection(); String sql = "{call rrr}"; try { CallableStatement cs = (CallableStatement)getConn.getConnection().prepareCall(sql); //cs.setString(1, "sdf"); cs.execute(); System.out.println(cs.getString(1)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
注意的幾個地方:
1:更改mysql鏈接帳號密碼
2:{call rrr} rrr爲儲存名字
6:右鍵run 運行程序
7:查看數據庫,多了許多數據
以下圖
成功建立一個儲存過程