网站建设知识
MySQL数据库知识之Java中实现预处理、批处理、大数据字段与存储过程
2025-07-22 10:01  点击:1

1.预处理、批处理

JdbcDemo.java

@Testpublic void saveAutoGenerateKeys(){//自动增长列,实行的也是唱票机制,即只会往后增加,即使上面的记录被删除,也不会再从新使用Connection con=ConnFactory.getConn();String sql="insert into book(name,price,birth) values('TomCat','35.8','2016-11-7 18:57:03')";try {Statement st=con.createStatement();st.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS);//这里如果不给Statement.RETURN_GENERATED_KEYS参数,记录会加进去数据库,但是在下面读取autoKey会出错,异常为java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement().                                                                                                                                                                                                                                                                    ResultSet rs=st.getGeneratedKeys();//获取自动增长列:rs中封装了所有自动生成的值while(rs.next()){int id =rs.getInt(1);System.out.println("当前自动增长列的id值为"+id);}} catch (Exception e) {e.printStackTrace();}}


会进数据库中

@Test//采用预处理语句public void saveAutoGenerateKeys2(){//这里用的是PreparedStatement与上一版本需要改动两处Connection con=ConnFactory.getConn();String sql="insert into book(name,price,birth) values(?,?,'2016-11-7 19:17:03')";try {PreparedStatement pst=con.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);//1.PreparedStatement.RETURN_GENERATED_KEYS这个参数值要在get的时候给pst.setString(1, "JSP");pst.setDouble(2, 28.9);pst.executeUpdate();//2.这里pst在执行executeUpdate方法时,不能给参数,否则便会调用父类Statement的方法了ResultSet rs=pst.getGeneratedKeys();while(rs.next()){int id =rs.getInt(1);System.out.println("当前自动增长列的id值为"+id);}} catch (Exception e) {e.printStackTrace();}}

数据库中:

@Test//批处理功能:Statement  主要是把要执行的sql语句全都放进st.addBatch()方法中去,然后执行st.executeBatch(),返回一个int[]数组,即每条sql语句执行后的影响public void batchDemo(){Connection con=ConnFactory.getConn();String sql="insert into book(name,price,birth) values('SpringMVC','22.5','2016-11-7 19:31:25')";try {Statement st=con.createStatement();for(int i=0;i<10;i++){st.addBatch(sql);}sql="update book set price=price*1.1 where price<40";st.addBatch(sql);int[] rows=st.executeBatch();for(int a:rows){System.out.println(a+"  row(s) affected");}} catch (SQLException e) {e.printStackTrace();}}


@Test//批处理功能:PreparedStatement  public void batchDemo2(){Connection con=ConnFactory.getConn();String sql="insert into book(name,price,birth) values(?,?,'2016-11-7 19:31:25')";try {PreparedStatement pst=con.prepareStatement(sql);for(int i=0;i<10;i++){pst.setString(1, "HTML"+i);pst.setDouble(2, 46+i);pst.addBatch();//这里同样不能放参数sql}int[] rows=pst.executeBatch();for(int a:rows){System.out.println(a+"  row(s) affected");}} catch (SQLException e) {e.printStackTrace();}finally{try {con.close();} catch (SQLException e) {e.printStackTrace();}}}


2.数据库中的大数据字段

JdbcDemo2.java

package cn.hncu;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import org.junit.Test;import cn.hncu.pubs.ConnFactory;//数据库中的大数据字段      "写"用PreparedStatement,"读"用Statementpublic class JdbcDemo2 {@Testpublic void saveColb(){Connection con=ConnFactory.getConn();try {PreparedStatement pst=con.prepareStatement("insert into note values(?,?)");pst.setInt(1, 1);File file=new File("./src/cn/hncu/JdbcDemo.java");pst.setAsciiStream(2, new FileInputStream(file));pst.executeUpdate();} catch (Exception e) {e.printStackTrace();}finally{try {con.close();} catch (SQLException e) {e.printStackTrace();}}}@Testpublic void readColb(){Connection con=ConnFactory.getConn();try {Statement st=con.createStatement();ResultSet rs=st.executeQuery("select * from note where id=1");while(rs.next()){InputStream in=rs.getAsciiStream(2);BufferedReader br=new BufferedReader(new InputStreamReader(in));String line=null;while((line=br.readLine())!=null){System.out.println(line);}}} catch (Exception e) {e.printStackTrace();}finally{try {con.close();} catch (SQLException e) {e.printStackTrace();}}}


文本写到数据库中:

读取:

@Testpublic void saveImg(){Connection con=ConnFactory.getConn();try {PreparedStatement pst=con.prepareStatement("insert into img values(?,?)");pst.setInt(1,2);File file=new File("5.jpg");//new file下面可做防护。注意:图片不能过大,否则会出com.mysql.jdbc.PacketTooBigException异常if(!file.exists()){return;}pst.setBinaryStream(2, new FileInputStream(file));pst.executeUpdate();} catch (Exception e) {e.printStackTrace();}finally{try {con.close();} catch (SQLException e) {e.printStackTrace();}}}@Testpublic void readImg(){//这里在读取图片的时候不方便在控制台输出,所以写到另外文件夹中Connection con=ConnFactory.getConn();try {Statement st=con.createStatement();ResultSet rs=st.executeQuery("select * from img where id=2");InputStream in=null;while(rs.next()){in=rs.getBinaryStream(2);}byte b[]=new byte[512];int len=0;File file=new File("d:/a");if(!file.exists()){file.mkdirs();}OutputStream out=new FileOutputStream(file+"/a.jpg");while((len=in.read(b))!=-1){out.write(b, 0, len);}in.close();out.close();} catch (Exception e) {e.printStackTrace();}finally{try {con.close();} catch (SQLException e) {e.printStackTrace();}}}}


存到数据库中:

读取:

3.存储过程

JdbcDemo3.java

package cn.hncu;import java.sql.CallableStatement;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Types;import org.junit.Test;import cn.hncu.pubs.ConnFactory;//存储过程public class JdbcDemo3 {//无参@Testpublic void callProcedureDemo(){Connection con=ConnFactory.getConn();try {CallableStatement cs=con.prepareCall("call p1()");//参数即是调用存储过程的sql语句,返回值是CallableStatement,同是Statement的子类ResultSet rs=cs.executeQuery();//若存储过程包含select查询,则用executeQuery()while(rs.next()){String name=rs.getString("name");System.out.println(name);}} catch (SQLException e) {e.printStackTrace();}}

无参查询结果:

//有输入参数@Testpublic void callProcedureDemo2(){Connection con=ConnFactory.getConn();try {//CallableStatement cs = con.prepareCall("call p2('P06','XYZ')"); //可以,但是参数写死了。如果要接收用户输入,则用占位符CallableStatement cs=con.prepareCall("call p2(?,?)");//用占位符写活cs.setString(1, "P04");cs.setString(2, "小雨");ResultSet rs=cs.executeQuery();//若存储过程包含select查询,则用executeQuery()while(rs.next()){String name=rs.getString("name");System.out.println(name);}} catch (SQLException e) {e.printStackTrace();}}

有输入参数查询:

//有输入、输出参数@Testpublic void callProcedureDemo3(){Connection con=ConnFactory.getConn();try {//CallableStatement cs = con.prepareCall("call p2('P06','XYZ')"); //可以,但是参数写死了。如果要接收用户输入,则用占位符CallableStatement cs=con.prepareCall("call p3(?,?,?)");//用占位符写活cs.setString(1, "P06");cs.setString(2, "菲菲");cs.registerOutParameter(3, Types.INTEGER);//这里指定第三个字符为输出参数,为其指定数据类型cs.executeUpdate();//同样不需要参数sqlint a=cs.getInt(3);//获取返回值System.out.println("返回值:"+a);} catch (SQLException e) {e.printStackTrace();}}}


控制台输出:

数据库数据为: