各位早上好
这个点刷到这篇文章的也都是这辈子有了
废话不多说上正文
通用部分代码:
package mybigpackage; // 可省略
import java.lang.*; // 基本类型包装、反射
import java.sql.*; // JDBC核心
import java.io.*; // 文件IO、流
import java.awt.*; // AWT图形界面
import javax.swing.*; // Swing图形界面
public class DBHelper {
private static final String DRIVER = "COM.ibm.db2.jdbc.app.DB2Driver";
private static final String URL = "jdbc:db2:sample"; // sample是数据库的名字
private static final String USER = "db2admin";
private static final String PASS = "db2admin";
private Connection conn = null;
// 处理SQL异常
private void handleSQLException(SQLException e) {
System.err.println("[SQL异常] " + e.getMessage());
System.err.println(" SQLState = " + e.getSQLState());
System.err.println(" ErrorCode= " + e.getErrorCode());
}
// 打开数据库连接
public void openConnection() {
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASS);
} catch (SQLException e) {
handleSQLException(e);
}
}
// 关闭所有资源
public void closeAll() {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
System.out.println("所有资源已关闭");
} catch (SQLException e) {
handleSQLException(e);
}
}
}
main函数的实现:
// 主函数实现
public static void main(String[] args) {
DBHelper db = new DBHelper();
db.openConnection();
Scanner sc = new Scanner(System.in); // 如果需要读取用户输入
try {
// 第1步:开启事务 + 定义SQL
db.conn.setAutoCommit(false); // 开启事务
String sql = "按照题目要求的SQL语句,可以带问号";
// 第2步:创建说明集
// 情况1:普通PreparedStatement
pstmt = db.conn.prepareStatement(sql);
// 情况2:支持滚动和更新
pstmt = db.conn.prepareStatement(
sql,
ResultSet.TYPE_SCROLL_INSENSITIVE, // 可滑动
ResultSet.CONCUR_UPDATABLE // 可更新
);
// 第3步:设置SQL语句中未知的值
// 情况1:直接写入固定值
pstmt.setType(num, value); // Type是类型,如Int;num表示第几列(从1开始);value是具体值
// 情况2:从用户输入获取值
System.out.print("请输入xxx:");
String inputXXX = sc.nextLine().trim(); // 读取数据并且忽略空白
// 第4步:更新数据
// 情况1:单次更新
int rows = pstmt.executeUpdate();
System.out.println("影响行数: " + rows);
// 情况2:批处理
for (int i = 0; i < n; i++) {
pstmt.setInt(1, empnoArray[i]);
pstmt.setString(2, nameArray[i]);
pstmt.addBatch();
}
int[] results = pstmt.executeBatch();
// 第5步:查询修改后的结果
rs = pstmt.executeQuery();
// 普通情况
rs.first(); // 定位到第一行
while (rs.next()) {
type LineNumber1 = rs.getType("LineName1");
type LineNumber2 = rs.getType("LineName2");
if (rs.wasNull()) { // 判空处理;这里写的不好,懒得改了
LineNumber1 = "空值";
}
System.out.println(LineNumber1 + LineNumber2 + "...");
}
// 倒序查询
if (rs.last()) { // 定位到最后一行
do {
// 和上面同理,循环体里面内容相同
} while (rs.previous()); // 从最后一行向前遍历
}
// 第6步:对结果集进行更新
// 方法1:FOR UPDATE 结合 WHERE CURRENT OF
sql = "XXX FOR UPDATE"; // 查询加锁
newsql = "XXX WHERE CURRENT OF CURSOR"; // 遍历中添加
// 方法2:直接通过ResultSet更新
rs.updateXXX(num, value);
rs.updateRow(); // 都是遍历中添加
// 第7步:提交事务
db.conn.commit();
System.out.println("事务已提交");
// 第8步:异常处理
} catch (SQLException e) {
handleSQLException(e);
try {
db.conn.rollback();
System.out.println("事务已回滚");
} catch (SQLException rollbackEx) {
handleSQLException(rollbackEx);
}
if ("22003".equals(e.getSQLState())) { // 数据溢出
System.err.println("数据溢出:值超出范围");
}
// 第9步:关闭资源
} finally {
db.closeAll();
}
}
关于大对象(Clob、Blob)处理
// ==========================下面是大文件处理=====================前三步照旧
I——Clob文本:
// CLOB写入(不需要结果集)
File clobFile = new File("C:/temp/resume.txt");
FileReader clobReader = new FileReader(clobFile);
pstmt.setCharacterStream(resume, clobReader, (int) clobFile.length());
int clobRows = clobPstmt.executeUpdate();
System.out.println("[CLOB] 写入影响行数: " + clobRows);
clobReader.close();
// CLOB读取(需要结果集)
rs = pstmt.executeQuery();
if (rs.next()) {
Clob resumeClob = rs.getClob("resume");
String resumeText = resumeClob.getSubString(1, (int) resumeClob.length());
System.out.println("[CLOB] 读取内容:\n" + resumeText);
}
II——Blob图片:
// BLOB写入(不需要结果集)
File blobFile = new File("C:/temp/photo.jpg");
FileInputStream blobFis = new FileInputStream(blobFile);
pstmt.setBinaryStream(photo, blobFis, (int) blobFile.length());
int blobRows = pstmt.executeUpdate();
System.out.println("[BLOB] 写入影响行数: " + blobRows);
blobFis.close();
// BLOB读取并写到本地
rs = pstmt.executeQuery();
if (rs.next()) {
Blob photoBlob = rs.getBlob("photo");
byte[] photoBytes = photoBlob.getBytes(1, (int) photoBlob.length());
// 写到本地
FileOutputStream fos = new FileOutputStream("C:/temp/outputPhoto.jpg");
fos.write(photoBytes);
fos.close();
}