一、JDBC的使用步骤
1、注册数据库的驱动
Class.forName("com.mysql.jdbc.Driver");
2、通过DriverManager获取数据库连接
//jdbc:subprotocol/subname
String url = "jdbc:mysql://127.0.0.1:3306/dbName?useUnicode=true&characterEncoding=utf8";
String user = "xxxx";
String password = "xxxx";
Connection connection = DriverManager.getConnection(url, user, password);
3、通过Connection对象获取Statement对象
Statement state = connection.createStatement();
4、使用Statement执行SQL语句
//return java.sql interface
ResautSet rs =state.executeQuery(sql);
5、操作ResultSet结果集
String order=rs.getString("order");
6、回收数据库资源
if (state != null) {
state.close();
}
state = null;
package cn.itcast.example01;
import java.sql.*;
/**
* @author wangyue
* @version 1.0
* @date 2019/7/8 10:08
* @describe: JDBC使用的步骤
* 1. 注册数据库的驱动 Class.forName("com.mysql.jdbc.Driver");
* 2.通过DriverManager获取数据库连接 connection = DriverManager.getConnection(url, user, password);
* 3.通过Connection对象获取Statement对象 state = connection.createStatement();
* 4.使用Statement执行SQL语句 rs =state.executeQuery(sql);
* 5. 操作ResultSet结果集 String order=rs.getString("order");
* 6.回收数据库资源 if (state != null) {
* state.close();
* }
* state = null;
*/
public class Example01 {
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement state = null;
ResultSet rs = null;
try {
//1. 注册数据库的驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.通过DriverManager获取数据库连接
String url = "jdbc:mysql://127.0.0.1:3306/dbName?useUnicode=true&characterEncoding=utf8"; //jdbc:subprotocol/subname
String user = "xxx";
String password = "xxxxxx";
connection = DriverManager.getConnection(url, user, password);
//3.通过Connection对象获取Statement对象
state = connection.createStatement();
//4.使用Statement执行SQL语句
String sql = "select * from pro_order";
rs = state.executeQuery(sql); //return java.sql interface
//5. 操作ResultSet结果集
while (rs.next()) {
String lineName = rs.getString("lineName");
String issueStatus = rs.getString("issueStatus");
String order = rs.getString("order");
String orderType = rs.getString("orderType");
Date planStartTime = rs.getDate("planStartTime");
System.out.println(lineName + " | " + issueStatus + " | " + order + " | " + orderType + " | " + planStartTime);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//6.回收数据库资源
if (connection != null) {
connection.close();
}
connection = null;
if (state != null) {
state.close();
}
state = null;
if (rs != null) {
rs.close();
}
rs = null;
}
}
}
输出
产线1 | 已下发 | WO01020301 | 正常 | 2019-03-01
产线1 | 已下发 | WO19020101 | 待再加工 | 2019-02-07
产线1 | 未下发 | WO19030101 | 待再加工 | 2019-03-02
产线1 | 已下发 | WO19030201 | 待再加工 | 2019-03-09
产线1 | 未下发 | WO19030301 | 正常 | 2019-03-21
产线1 | 未下发 | WO19032801 | 正常 | 2019-03-29
产线1 | 已下发 | WO19032901 | 正常 | 2019-03-30
产线1 | 未下发 | WO19042801 | 正常 | 2019-03-29
产线1 | 未下发 | WO19050101 | 待再加工 | 2019-03-02
产线1 | 未下发 | WO19050102 | 待再加工 | 2019-03-02
产线1 | 已下发 | WO19052301 | 正常 | 2019-06-01
产线1 | 未下发 | WO19052801 | 正常 | 2019-03-29