Java实训笔记(十)之JDBC篇

一、JDBC概述

JDBC:是java操作数据库的技术,在此技术中提供了一组API来实现对不同数据源的数据库操作。

JDBC API中包括java.sql包和javax.sql包,其中java.sql称为核心包,javax.sql称为扩展包。

我们这里主要讲解java.sql包。

java.sql 包中包含用于以下方面的 API:



二、JDBC详解

1、java操作数据库的步骤:

1、 驱动注册:

Class.forName(驱动)或者Class.forName(驱动).newInstance()

首先明确连接数据源是什么,根据不同的数据源下载不同的驱动程序,在这里我们选用mysql数据源。然后在项目中添加mysql的驱动程序。驱动字符串的获得

2、 建立与数据库的连接

3、 通过不同Statement来执行sql语句。

a) 如果带参数的sql语法通过PreparedStatement来执行;

b) 如果sql是通过拼接的方式,可以使用Statement或者PreparedStatement 来执行;

c) 如果执行是存储过程,使用CallableStatement来执行。

Java操作msyql

说明:在这里选用两种操作:select和insert,sql语句也采用两种方式一种拼接一个带参数。

1、 执行查询操作之前需要进行驱动注册和数据库的连接:

Class.forName(“com.mysql.jdbc.Driver”);

String url =”jdbc:mysql://localhost:3306/student”;

String user =”root”;

String pwd =”123”;

Connection con = DriverManager.getConnection(url,user,pwd);

2、 通过不同Statement来执行,在这里我们首先使用Statement来执行。

Statement sta = con.createStatement();//

//根据操作的不同选用不同的方法,如果执行的查询操作,有结果集的返回,在这里选、、//用executeQuery方法,如果是执行的增加、删除、修改,返回的时影响行数,选用//executeUpdate()方法。

Scanner input = new Scanner(System.in);

String name = input.next();

String sql =”select * from stdinfo where sname=’”+name+”’”;

ResultSet rs = sta.executeQuery(sql);

While(rs.next()){

System.out.println(rs.getString(1)+”:”+rs.getString(2));

}

上面的程序中使用的拼接sql的方法,在此方式,容易出现错误,当给姓名赋值,如果输入” ‘张三”这种形式,就会出现异常。要避免这种情况,我们使用带参数的sql语句。

StringBuffer sb = new StringBuffer();

Sb.append(“select * from stdinfo where sname=?”)

Scanner input = new Scanner(System.in);

String name= input.next();

PreparedStatement pre = con.prepareStatement(sb.toString());

Pre.setString(1,name);

ResultSet rs = pre.executeQuery();

While(rs.next()){

System.out.println(rs.getString(1));

}

以上的示例讲解了查询的执行,这种查询无论是简单的查询,还是多表查询,执行方式是不变,唯一变化的就是sql而已。在这里就不在赘述。

下面通过示例讲解insert的操作。

第一种方式:拼接sql

Statement sta = con.createStatement();//

StringBuffer sql = new StringBuffer();//假定是通过界面的文本框输入值

sql.append("insert into stdinfo values('");

sql.append( txtId.getText()+"','"+txtName.getText()+"','");

sql.append(txtSex.getText()+"','");

sql.append(txtAddress.getText()+"')");

int count = sta.executeUpdate(sql.toString());

if(count>0){

JOptionPane.showMessageDialog(null, "成功");

}

第二种方式:带参数的方式

StringBuffer sql = new StringBuffer();

sql.append("insert into stdinfo values(?,?,?,?)");

PreparedStatement pre = con.prepareStatement(sql.toString());

pre.setString(1, txtId.getText());

pre.setString(2, txtName.getText());

pre.setString(3, txtSex.getText());

pre.setString(4, txtAddress.getText());

int count = pre.executeUpdate();

在这里以insert操作为例,其他的操作与insert操作唯一不同的时sql语句不同。

可滚动的结果集和可更新的结果集

Statement sta= con.createStatement(intresultSetType,

intresultSetConcurrency)

参数:

resultSetType- 结果集类型,它是 ResultSet.TYPE_FORWARD_ONLY(只能向前读取)、ResultSet.TYPE_SCROLL_INSENSITIVE(可滚动的,对数据库操作不敏感) 或 ResultSet.TYPE_SCROLL_SENSITIVE(可滚动的,堆数据库操作敏感) 之一

resultSetConcurrency- 并发类型;它是 ResultSet.CONCUR_READ_ONLY(只读) 或 ResultSet.CONCUR_UPDATABLE 之一(可更新)

PreparedStatement是在创建PreparedStatemnt这句中。

2、ResultSet详解

3、Java读取配置文件

注意配置文件要src的根目录中。

代码:

import java.io.IOException;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.util.Properties;

public class GetProperties {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

try {

Connection con = null;

try {

con = new GetProperties().getConn();

System.out.println("连接成功!");

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

try {

con.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

} catch (IOException e) {

}

}

public Connection getConn() throws IOException, ClassNotFoundException,

SQLException {

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

// System.out.println(driver);

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url, user, pwd);

}

}

4、Java中文乱码问题

解决问题方法:

1、 修改mysql的安装目录下的my.ini文件,把其中的default-character-set改为gbk,然后在服务管理器中重新启动mysql的服务;

2、 设定mysql字符编码(在前面的java笔记中有介绍),查看数据库和表的字符编码;



1、 更改db.properties的配置信息,由原来url=jdbc:mysql://localhost:3306/student改为url=jdbc:mysql://localhost:3306/student?user=root&password=123&useUnicode=true&characterEncoding=GBK;

2、 设定字符的编码;String name = new String("我们".getBytes(),"GBK");

表结构:



public class Demo{

public static void main(String[]args){

new Demo().addInfo();

new Demo().getInfo();

}

public void getInfo(){

Connection con;

try {

con = getConn();

Statement sta = con.createStatement();

String sql ="select * from t";

ResultSet rs=sta.executeQuery(sql);

while(rs.next()){

System.out.println(rs.getString(1));

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void addInfo(){

Connection con;

try {

con = getConn();

String sql ="insert into t values(?)";

PreparedStatement sta = con.prepareStatement(sql);

String name = new String("我们".getBytes(),"GBK");

sta.setString(1, name);

int count=sta.executeUpdate();

if(count>0){

System.out.println("s");

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public Connection getConn() throws IOException, ClassNotFoundException, SQLException{

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

//System.out.println(driver);

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url);

}

}

1、读写图像

1、概述:图像信息是采用二进制的形式进行存储的。在C/S程序中,如果需要保存头像信息,就需要把图像的信息存入到数据库中,在B/S程序中,如果要保存图片信息,图片首先会上传服务器中,然后在数据库中保存图片的路径即可。

2、Mysql类型,有四种类型用来保存图片,分别:

  ·tinyblob:仅255个字符

  ·blob:最大限制到65K字节

  ·mediumblob:限制到16M字节

·longblob:可达4GB

根据图片的大小选择合适的数据类型。

3、示例

1、写图像:

表结构


import java.awt.Image;

import java.io.*;

import java.sql.*;

import java.util.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class ImageRun {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

new ImageRun().addImg();

}

//addImg方法实现图像写入

public void addImg(){

File f = new File("c:\\car.jpg");

Connection con =null;

try {

FileInputStream fin = new FileInputStream(f);

con = getConn();

String sql ="insert into img(imgSave) values(?)";

PreparedStatement pre = con.prepareStatement(sql);

pre.setBinaryStream(1, fin, (int)f.length());

//System.out.println(f.length());

int count=pre.executeUpdate();

if(count>0){

System.out.println("ok");

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

finally{

try {

con.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

//getConn通过读取db.properties文件中数据库配置信息

public Connection getConn() throws IOException, ClassNotFoundException, SQLException{

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

System.out.println(driver);

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url,user,pwd);

}

}

//db.properties文件配置信息

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/student?user=root&password=123&useUnicode=true&characterEncoding=GBK

2、读图像:

import java.awt.Image;

import java.io.*;

import java.sql.*;

import java.util.*;

import javax.imageio.ImageIO;

import javax.swing.*;

public class ImageRun {

public static void main(String[] args) {

// TODO Auto-generated method stub

//读取第一张图片在JLabel中显示

Frame frame = new JFrame();

JLabel lbl = new JLabel();

lbl.setIcon(new ImageRun().viewImg());

frame.add(lbl);

frame.setSize(400,400);

frame.setVisible(true);

}

//方法读取图像返回ImageIcon

public ImageIcon viewImg(){

Connection con =null;

Image img=null;

try {

con=getConn();

Statement sta = con.createStatement();

String sql = "select imgSave from img";

ResultSet rs = sta.executeQuery(sql);

rs.next();

if(rs.next()){

Blob blob = rs.getBlob(1);

img = ImageIO.read(blob.getBinaryStream());

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

return new ImageIcon(img);

}

public Connection getConn() throws IOException, ClassNotFoundException, SQLException{

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

System.out.println(driver);

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url,user,pwd);

}

}

1、执行存储过程

1、概述:
2、示例
1:执行无参数的存储过程。

存储过程结构:其中view_test是mysql中的视图,请参见java实训笔记(九)。


代码:

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import java.sql.*;

public class ProcedureTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

ProcedureTest proc = new ProcedureTest();

try {

Connection con = proc.getConn();

CallableStatement call = con.prepareCall("{call sp_t1}");

ResultSet rs = call.executeQuery();

While(rs.next()){

System.out.println(“学生信息如下:”+rs.getString(1)+”:”+rs.getString(2)+”:”+rs.getString(3)+”:”+rs.getString(4));

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public Connection getConn() throws IOException, ClassNotFoundException,

SQLException {

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url, user, pwd);

}

}

2:带输入参数的存储过程。

存储过程结构:


代码:

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import java.sql.*;

public class ProcedureTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

ProcedureTest proc = new ProcedureTest();

try {

Connection con = proc.getConn();

CallableStatement call = con.prepareCall("{call sp_t2(?,?)}");

call.setInt(1, 10);

call.setInt(2, 30);

ResultSet rs = call.executeQuery();

if(rs.next()) System.out.println(rs.getInt(1));

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public Connection getConn() throws IOException, ClassNotFoundException,

SQLException {

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url, user, pwd);

}

}

3:带输入参数和输出参数的存储过程。

存储过程结构:


代码:

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import java.sql.*;

public class ProcedureTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

ProcedureTest proc = new ProcedureTest();

try {

Connection con = proc.getConn();

CallableStatement call = con.prepareCall("{call sp_t3(?,?,?)}");

call.setInt(1, 20);

call.setInt(2, 30);

call.registerOutParameter(3, Types.INTEGER);

call.execute();

System.out.println(call.getInt(3));

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public Connection getConn() throws IOException, ClassNotFoundException,

SQLException {

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url, user, pwd);

}

}

4:存储过程多个查询结果。

说明:多个select结果时使用getMoreResults判断,如果是操作语句(增加、删除、修改)使用getUpdateCount判断。


代码:

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import java.sql.*;

public class ProcedureTest {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

ProcedureTest proc = new ProcedureTest();

try {

Connection con = proc.getConn();

CallableStatement call = con.prepareCall("{call sp_t4}");

boolean flag=call.execute();

if (flag) {

ResultSet rs = call.getResultSet();

while (rs.next()) {

System.out.println(rs.getString(1));

}

while(call.getMoreResults()){

ResultSet rs1 = call.getResultSet();

while (rs1.next()) {

System.out.println(rs1.getString(2));

}

}

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public Connection getConn() throws IOException, ClassNotFoundException,

SQLException {

Properties props = new Properties();

InputStream in = Properties.class.getResourceAsStream("/db.properties");

props.load(in);

in.close();

String driver = props.getProperty("driver");

String url = props.getProperty("url");

String user = props.getProperty("user");

String pwd = props.getProperty("pwd");

Class.forName(driver);

return DriverManager.getConnection(url, user, pwd);

}

}




你可能感兴趣的:(Java实训笔记(十)之JDBC篇)