您的位置:首页 > 大数据

补MySQL第六天----Java中实现预处理、批处理、大数据字段与存储过程

2016-11-07 21:39 465 查看

1.预处理、批处理

JdbcDemo.java

<span style="font-size:14px;">@Test
public 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();
}
}</span>


会进数据库中



 

<span style="font-size:14px;">@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();
}
}</span>

 



数据库中:



 

<span style="font-size:14px;">@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();
}
}</span>




 

<span style="font-size:14px;">@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();
}
}
}
</span>




 

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

JdbcDemo2.java

<span style="font-size:14px;">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,"读"用Statement
public class JdbcDemo2 {
/*
* 有关文本型大数据的名称:数据库中称text,clob  java中称AsciiStream
* 文本型大数据类型:tinytext,text,mediumtext,longtext四种,每种都有其支持的最大字符数(MySQL中VARCHAR(21845)最大,后面则是mediumtext
*
*  CREATE TABLE note(
id INT,
note TEXT
);
*/
@Test
public 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();
}
}

}

@Test
public 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();
}
}
}
</span>


文本写到数据库中:



读取:



 

 

<span style="font-size:14px;">/*
* 二进制大字段  binary lob----blob   Java中称binaryStream
* CREATE TABLE img(
id INT,
img BLOB
);
*/
@Test
public 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();
}
}
}

@Test
public 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();
}
}
}
}</span>


存到数据库中:



 

读取:



 

 

3.存储过程

JdbcDemo3.java

 

<span style="font-size:14px;">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 {

//无参
@Test
public 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();
}
}</span>

 

无参查询结果:



 

<span style="font-size:14px;">//有输入参数
@Test
public 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();
}
}
</span>

 

有输入参数查询:



 

<span style="font-size:14px;">//有输入、输出参数
@Test
public 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();//同样不需要参数sql
int a=cs.getInt(3);//获取返回值
System.out.println("返回值:"+a);
} catch (SQLException e) {
e.printStackTrace();
}
}

}</span>


控制台输出:



数据库数据为:

 



 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息