0.介绍
JDBC(Java DataBase Connectivity,Java数据库连接)是SUN公司制定的一套接口,接口大多在java.sql.*下。
想要通过JDBC连接数据库需要配置mysql的驱动依赖。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
从JDBC4.0(JDK6)开始不再需要主动加载驱动。JDBC4.0的驱动jar文件必须包含一个java.sql.Driver,它位于jar文件的META-INF/services目录下。这个文件里每一行便描述了一个对应的驱动类。在启动项目或是服务时,会判断当前classspath中的所的jar包,并检查他们META-INF目录下,是否包含services文件夹,如果包含,就会将里面的配置加载成相应的服务。
1.查询
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class A {
public static void main(String[] args) {
String JDBC_URL = "jdbc:mysql://localhost:3306/learnjdbc";
String JDBC_USER = "root";
String JDBC_PASSWORD = "123456";
Connection conn = null;
try {
// 查看驱动
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
System.out.println(drivers.nextElement());
}
// 获取连接
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
// (1)createStatement只能在SQL中拼接参数,容易造成SQL注入;
// Statement statement = conn.createStatement();
// ResultSet rs = statement.executeQuery("SELECT id, name, gender, grade, score FROM students WHERE gender=1");
// (2)prepareStatement 可以在SQL中用?替换变量,保证SQL安全问题,防止SQL注入
PreparedStatement ps = conn.prepareStatement("SELECT name, gender, grade, score FROM students WHERE gender=? AND grade=?");
ps.setObject(1, "M"); // 注意:索引从1开始
ps.setObject(2, 3);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
int gender = rs.getInt("gender");
int grade = rs.getInt("grade");
int score = rs.getInt("score");
System.out.println(name + ' ' + gender + ' ' + grade + ' ' + score + ' ');
}
} catch (SQLException e) {
System.out.println("Problem getting connection"+ e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("Problem closing connection"+e);
}
}
}
}
2.插入
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class B {
public static void main(String[] args) {
String JDBC_URL = "jdbc:mysql://localhost:3306/learnjdbc";
String JDBC_USER = "root";
String JDBC_PASSWORD = "123456";
Connection conn = null;
try {
// 查看驱动
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
System.out.println(drivers.nextElement());
}
// 获取连接
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
PreparedStatement ps = conn.prepareStatement("INSERT INTO students (name, gender, grade, score) VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
int i = 1;
ps.setObject(i++, "Mack");
ps.setObject(i++, 0);
ps.setObject(i++, 5);
ps.setObject(i++, 100);
int n = ps.executeUpdate(); // 1
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
long id = rs.getLong(1);
System.out.println(id);
}
} catch (SQLException e) {
System.out.println("Problem getting connection"+ e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("Problem closing connection"+e);
}
}
}
}
3.更新
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class C {
public static void main(String[] args) {
String JDBC_URL = "jdbc:mysql://localhost:3306/learnjdbc";
String JDBC_USER = "root";
String JDBC_PASSWORD = "123456";
Connection conn = null;
try {
// 查看驱动
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
System.out.println(drivers.nextElement());
}
// 获取连接
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
PreparedStatement ps = conn.prepareStatement("UPDATE students SET name=? WHERE id=?");
int i = 1;
ps.setObject(i++, "Jack"); // 注意:索引从1开始
ps.setObject(i++, 1);
int n = ps.executeUpdate(); // 返回更新的行数
} catch (SQLException e) {
System.out.println("Problem getting connection"+ e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("Problem closing connection"+e);
}
}
}
}
4.删除
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class D {
public static void main(String[] args) {
String JDBC_URL = "jdbc:mysql://localhost:3306/learnjdbc";
String JDBC_USER = "root";
String JDBC_PASSWORD = "123456";
Connection conn = null;
try {
// 查看驱动
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
System.out.println(drivers.nextElement());
}
// 获取连接
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
PreparedStatement ps = conn.prepareStatement("DELETE FROM students WHERE id=?");
int i = 1;
ps.setObject(i++, 1);
int n = ps.executeUpdate(); // 返回更新的行数
} catch (SQLException e) {
System.out.println("Problem getting connection"+ e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("Problem closing connection"+e);
}
}
}
}
5.事务
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class E {
public static void main(String[] args) throws SQLException {
String JDBC_URL = "jdbc:mysql://localhost:3306/learnjdbc";
String JDBC_USER = "root";
String JDBC_PASSWORD = "123456";
Connection conn = null;
try {
// 查看驱动
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
System.out.println(drivers.nextElement());
}
// 获取连接
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
conn.setAutoCommit(false);
PreparedStatement ps1 = conn.prepareStatement("DELETE FROM students WHERE id=?");
ps1.setObject(1, 4);
int n1 = ps1.executeUpdate(); // 返回更新的行数
System.out.println(n1);
PreparedStatement ps2 = conn.prepareStatement("DELETE FROM students WHERE id=?");
ps2.setObject(1, 4);
int n2 = ps2.executeUpdate(); // 返回更新的行数
System.out.println(n2);
conn.commit();
} catch (SQLException e) {
conn.rollback();
} finally {
conn.setAutoCommit(true);
conn.close();
}
}
}
6.批处理
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class F {
public static void main(String[] args) throws SQLException {
String JDBC_URL = "jdbc:mysql://localhost:3306/learnjdbc";
String JDBC_USER = "root";
String JDBC_PASSWORD = "123456";
Connection conn = null;
try {
// 查看驱动
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
System.out.println(drivers.nextElement());
}
// 获取连接
conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
PreparedStatement ps = conn.prepareStatement("DELETE FROM students WHERE id=?");
int[] i1 = new int[]{5,6,7,8,9,10};
for (int i : i1) {
ps.setObject(1, i);
ps.addBatch();
}
int[] n1 = ps.executeBatch(); // 返回更新的行数
System.out.println(n1);
} catch (SQLException e) {
} finally {
conn.close();
}
}
}
7.JDBC连接池
JDBC连接池有一个标准的接口javax.sql.DataSource,注意这个类位于Java标准库中,但仅仅是接口。要使用JDBC连接池,我们必须选择一个JDBC连接池的实现。常用的JDBC连接池有:
- HikariCP
- DBCP(BasicDataSurce)
- C3P0
- BoneCP
- Druid
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.1</version>
</dependency>
<!-- 如不加载slf4j,HikariCP会报错 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
<scope>compile</scope>
</dependency>
</dependencies>
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import java.sql.*;
public class dataSource {
public static void main(String[] args) {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/learnjdbc");
config.setUsername("root");
config.setPassword("123456");
config.addDataSourceProperty("connectionTimeout", "1000"); // 连接超时:1秒
config.addDataSourceProperty("idleTimeout", "60000"); // 空闲超时:60秒
config.addDataSourceProperty("maximumPoolSize", "10"); // 最大连接数:10
DataSource ds = new HikariDataSource(config);
Connection conn = null;
try {
conn = ds.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT id,name FROM t1 WHERE id=? AND name=?");
ps.setInt(1, 1); // 注意:索引从1开始
ps.setString(2, "h");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("" + id + " " + name);
}
} catch (SQLException e) {
System.out.println("Problem getting connection"+ e);
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("Problem closing connection"+e);
}
}
}
}