java JDBC 进行增删改查
1、读取配置文件中的参数
private static String driver = ReadPropertiesUtils.getValue("jdbc.driver","data.properties"); private static String url = ReadPropertiesUtils.getValue("jdbc.url","data.properties"); private static String userName = ReadPropertiesUtils.getValue("jdbc.userName","data.properties"); private static String password = ReadPropertiesUtils.getValue("jdbc.password","data.properties");
//创建的数据库连接 private static Connection conn = null;
ReadPropertiesUtils.class

package inter7.utils; import org.springframework.core.io.support.PropertiesLoaderUtils; import java.util.Enumeration; import java.util.HashMap; import java.util.Properties; /** * @Auther: yxchun * @Date: 2022/5/22 - 18:20 * @Description:inter403.utils * @Version:1.0 */ public class ReadPropertiesUtils { private static HashMap<String, String> propertiesMap = new HashMap<String, String>(); private static void loadlProperty(Properties props) { @SuppressWarnings("rawtypes") Enumeration en = props.propertyNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); String value = props.getProperty(key); propertiesMap.put(key, value); } } public static String getValue(String key, String fileName) { Properties prop = null; try { // 通过Spring中的PropertiesLoaderUtils工具类进行获取 prop = PropertiesLoaderUtils.loadAllProperties(fileName); loadlProperty(prop); } catch (Exception e) { e.printStackTrace(); } return propertiesMap.get(key); } public static void main(String[] args) { System.out.println(getValue("rechargeFilePath","filePath.properties")); } }
data.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/testspringboot?allowPublicKeyRetrieval=true&useSSL=false jdbc.userName=root jdbc.password=root
2、获取数据库连接
public static Connection getConnection() throws SQLException { try { Class.forName(driver); conn = DriverManager.getConnection(url, userName, password); System.out.println("register driver success"); if (conn == null) { System.out.println("conn == null"); } return conn; } catch (ClassNotFoundException e) { System.out.println("register driver failed"); e.printStackTrace(); return null; }
3、查询,查询结果返回Lis<T>
/** * 返回多条记录 */ public static <T> List<T> selectParam(Class<T> tClass, String sql, Object... args) { ResultSet rs = null; PreparedStatement ps = null; //创建集合对象 ArrayList<T> list = new ArrayList<>(); try { ps = getConnection().prepareStatement(sql); for (int i = 0; i < args.length; i++) { ps.setObject(i+1,args[i]); } //执行获取结果集 rs = ps.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); //获取列数 int columnCount = rsmd.getColumnCount(); while (rs.next()) { T t = tClass.newInstance(); for (int i = 0; i < columnCount; i++) { //获取列值 Object columnValue = rs.getObject(i + 1); //获取列的别名 String columnLable = rsmd.getColumnLabel(i + 1); //利用反射为每一个对象进行赋值操作赋值 Field field = tClass.getDeclaredField(columnLable); field.setAccessible(true); field.set(t, columnValue); } list.add(t); } return list; } catch (Exception e) { System.out.println(e.getMessage()); } finally { try { closeResoure(conn, ps, rs); } catch (Exception e) { System.out.println(e.getMessage()); } } return null; }
4、修改、新增、删除 ,返回执行结果
public static boolean updatePOJO(String sql) throws SQLException { PreparedStatement stat = getConnection().prepareStatement(sql); int i = stat.executeUpdate(); closeResoure(conn,stat); if(i==1){ return true; }else{ return false; } }
5、关闭资源

/** * 关闭资源 */ public static void closeResoure(Connection conn, PreparedStatement ps) { try { if (ps != null) { ps.close(); } } catch (SQLException throwables) { // throwables.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } } /** * 重载一下关闭流,方便查询操作时使用 */ public static void closeResoure(Connection conn, PreparedStatement ps, ResultSet rs) { try { if (ps != null) { ps.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } try { if (rs != null) { rs.close(); } } catch (SQLException throwables) { throwables.printStackTrace(); } }
6、测试增删改查
public static void main(String[] args) throws SQLException { //测试查询,封装后查询将会根据别名 // String sql = "select uid as uid,nick as nick from j_user where crtime like ?"; // List<JUser> list = selectParam(JUser.class,sql, "2019-12%%"); // System.out.println("in main() \t list="+list.size()); // for (JUser user:list){ // System.out.println(user.getUid()+"\t"+user.getNick()); // } //测试update // String sql="update j_user set nick='我是张三2' where uid='123@qq.com'"; //测试add String sql="INSERT INTO `j_user`(`id`, `uid`, `password`, `nick`, `img`, `signin`, `signinTime`, `age`, `sex`, `info`, `state`, `crtime`, `uptime`) VALUES ('17bd294a109b48afb4f6024842332c47', '123@qq.com', '202cb962ac59075b964b07152d234b70', 'yangchun', '20191204100400.jpeg', 1, '2019-11-24 20:07:49', 18, 1, NULL, 3, '2019-11-24 20:04:48', '2019-11-24 20:04:48');"; //测试delete // String sql="delete from j_user where uid='123@qq.com'"; System.out.println(updatePOJO(sql)); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~