Java的JDBC编程
1.Java的数据库编程:JDBC
1.1 JDBC介绍
- JDBC,即Java Database Connectivity,专门处理java数据库连接。
1.2 JDBC工作原理
1.3 各个对象的生命周期
1.3.1 DataSource
1.3.2 Connection
- 每次打一个电话,用一个对象;注意:Connection对象不是线程安全的,保证多个线程之间共享一个对象;
1.3.3 PrepareStatement对象和 ResultSet对象
- 在一次Connection里,可以多次说,保证每次都正确的close就可以;
2.JDBC使用
2.1 JDBC开发案例
2.1.1 执行查询操作
-
package com.cc;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JDBCDemo1 {
public static void main(String[] args) throws SQLException {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setServerName("127.0.0.1");
mysqlDataSource.setPort(3306);
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("123456");
mysqlDataSource.setDatabaseName("db_11_24");
mysqlDataSource.setCharacterEncoding("utf8");
mysqlDataSource.setServerTimezone("Asia/Shanghai");
mysqlDataSource.setUseSSL(false);
Connection connection1 = null;
try {
connection1 = mysqlDataSource.getConnection();
String sql = "select * from exam_result order by id";
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection1.prepareStatement(sql);
ResultSet resultSet = null;
try {
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
double chinese = resultSet.getDouble("chinese");
double math = resultSet.getDouble("math");
double english = resultSet.getDouble("english");
System.out.printf("%d %s %.1f %.1f %.1f\n", id, name, chinese, math ,english);
}
} finally {
if (resultSet != null) {
resultSet.close();
}
}
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
}
} finally {
if (connection1 != null) {
connection1.close();
}
}
}
}
2.1.2 执行非查询类操作
-
package com.cc;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.*;
public class JDBCNotSelectDemo {
public static void main(String[] args) throws SQLException {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/db_11_24?characterEncoding=utf8&useSSL=false&serverTimezonr=Asia/Shanghai");
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("123456");
try (Connection connection = mysqlDataSource.getConnection()) {
String sql = "insert into exam_result (name, chinese, math, english) values ('二郎神', 38, 99, 78.5)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
int affectRow = preparedStatement.executeUpdate();
System.out.println("影响行数:" + affectRow);
try (ResultSet resultSet = preparedStatement.getGeneratedKeys()) {
resultSet.next();
int pk = resultSet.getInt(1);
System.out.println(pk);
}
}
}
}
public static void main1(String[] args) throws SQLException {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/db_11_24?characterEncoding=utf8&useSSL=false&serverTimezonr=Asia/Shanghai");
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("123456");
try (Connection connection = mysqlDataSource.getConnection()) {
String sql = "insert into exam_result (name, chinese, math, english) values ('哪吒', 38, 99, 78.5)";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
int affectRow = preparedStatement.executeUpdate();
System.out.println("影响行数:" + affectRow);
}
}
}
}
2.1.3 举例:类似于SQL的命令行界面
-
读取用户的一行输入(一条SQL); -
执行这条SQL,
- 如果失败,给出异常原因,不结束;
- 如果查询,给出结果;
- 如果不是查询,给出影响行数;
-
package com.cc;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.*;
import java.util.Scanner;
public class MySQLClientCLI {
private static Connection connection = null;
public static void main(String[] args) throws SQLException {
initConnection();
Scanner s = new Scanner(System.in);
System.out.print("> ");
while (s.hasNextLine()) {
String sql = s.nextLine().trim();
if (sql.isEmpty()) {
System.out.print("> ");
continue;
}
excuteSql(sql);
System.out.print("> ");
}
}
private static void initConnection() throws SQLException {
MysqlDataSource ds = new MysqlDataSource();
ds.setServerName("localhost");
ds.setPort(3306);
ds.setUser("root");
ds.setPassword("123456");
ds.setDatabaseName("db_11_24");
ds.setCharacterEncoding("utf8");
ds.setServerTimezone("Asia/Shanghai");
ds.setUseSSL(false);
connection = ds.getConnection();
}
private static void excuteSql(String sql) {
try (PreparedStatement s = connection.prepareStatement(sql)) {
if (isQuerySql(sql)) {
try (ResultSet rs = s.executeQuery()) {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
String name = metaData.getColumnName(i);
sb.append(name);
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
System.out.println(sb.toString());
while (rs.next()) {
StringBuilder sbValue = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
String column = rs.getString(i);
sbValue.append(column);
sbValue.append(", ");
}
sbValue.delete(sbValue.length() - 2, sbValue.length());
System.out.println(sbValue.toString());
}
}
} else {
int an = s.executeUpdate();
System.out.println("影响行数:" + an);
}
} catch (SQLException exc) {
String reason = exc.getMessage();
System.out.println(reason);
}
}
private static boolean isQuerySql(String sql) {
String[] s = sql.split(" ");
String firstWord = s[0].toLowerCase();
return firstWord.equals("show") || firstWord.equals("select");
}
}
2.2 JDBC使用步骤总结
- 创建数据库连接Connection;
- 创建操作命令Statement;
- 使用操作命令来执行SQL;
- 处理结果集ResultSet;
- 释放资源.
|