1:创建数据库Student
共两个字段 id和sname
主键Id ,自动递增
sname ,字符类型varchar
2:打开navicat
3:在BEGIN ,END中输入:
declare n bigint;
set n = 201121029684;
while n <= 201121029694
do
insert into student(sname) values(n);
set n = n + 1;
end while;
如下图
保存名字为rrr的储存
4:myeclipse中新建一个Java工程
如test
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:查看数据库,多了许多数据
如下图
成功创建一个储存过程