java处理数据库的CRUD

时间:2025-02-24 00:04:50
package com.lhy.jdbc.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; /**
*
* 增删改查
* @author hy
*
*/
public class CRUD {
public static void main(String[] args) {
//create();
//read();
//update();
delete(); } /**
* 查询
*/
static void read() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null; try {
// 建立连接,JdbcUtil工具类请看我的另一篇博客
conn = JdbcUtil.getConnection();
// 创建语句
stmt = conn.createStatement();
/**
* 执行语句,一般不建议直接写select *,可读性不好。
*/
rs = stmt.executeQuery("select * from user"); // 处理结果
while (rs.next()) { System.out.println(rs.getString("username") + "\t"
+ rs.getString("password"));
} } catch (SQLException e) { e.printStackTrace();
} finally {
JdbcUtil.close(rs);
JdbcUtil.close(stmt);
JdbcUtil.close(conn);
} }
/**
* insert into插一条记录
*/
static void create(){ Connection conn = null;
Statement stmt = null; try {
// 建立连接
conn = JdbcUtil.getConnection();
// 创建语句
stmt = conn.createStatement(); String sql = "insert into user values('你好','147',1000)"; //执行语句,返回值是int 几行被插入
stmt.executeUpdate(sql);
//int i = stmt.executeUpdate(sql);
//System.out.println("i="+i); } catch (SQLException e) { e.printStackTrace();
} finally { JdbcUtil.close(stmt);
JdbcUtil.close(conn);
} } /**
* 更新
*/ static void update(){ Connection conn = null;
Statement stmt = null; try {
// 建立连接
conn = JdbcUtil.getConnection();
// 创建语句
stmt = conn.createStatement();
// 执行语句
String sql = "update user set money = money + 100";
// int i = stmt.executeUpdate(sql);
// System.out.println("i="+i); } catch (SQLException e) { e.printStackTrace();
} finally { JdbcUtil.close(stmt);
JdbcUtil.close(conn);
} } static void delete(){ Connection conn = null;
Statement stmt = null; try {
// 建立连接
conn = JdbcUtil.getConnection();
// 创建语句
stmt = conn.createStatement();
// 执行语句
String sql = "delete from user where money <600";
int i = stmt.executeUpdate(sql);
System.out.println("i="+i); } catch (SQLException e) { e.printStackTrace();
} finally { JdbcUtil.close(stmt);
JdbcUtil.close(conn);
}
}
}