标签:rac jdbcutil util 类加载 static creat set 分享 nts
首先,注册驱动
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()); //注意,mysql5时用com.mysql.jdbc.Driver //但是mysql8以后要用com.mysql.cj.jdbc.Driver
然后,建立连接
Connection conn = DriverManager.getConnection(url, user, password); /* user和password没什么好说的 url的格式为: "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC" 但是在mysql5的时候,url要写成: "jdbc:mysql://localhost:3306/数据库名" */
接着,创建statement,跟数据库打交道,一定需要这个对象:
Statement st = conn.createStatement();
然后就可以执行sql语句了:
String sql = "select * from users;"; ResultSet rs = st.executeQuery(sql); while(rs.next()) { String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println("name=" + name + ", age=" + age); }
最后,要把使用的资源关闭:
rs.close();
st.close();
conn.close();
关于注册驱动:
关于资源关闭:
配置文件jdbc.properties放在src目录下
package com.wbytts.util; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; public class JDBCUtils { static String driverClass = null; static String url = null; static String name = null; static String password = null; static { try { //建立一个属性配置对象 Properties properties = new Properties(); //使用类加载器,去获取src底下的文件 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"); //导入输入流 properties.load(is); //读取属性 driverClass = properties.getProperty("driverClass"); url = properties.getProperty("url"); name = properties.getProperty("name"); password = properties.getProperty("password"); } catch (IOException e) { e.printStackTrace(); } } public static Connection getConn() { Connection conn = null; try { Class.forName(driverClass); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", name, password); } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 释放资源 * @param conn * @param st * @param rs */ public static void release(Connection conn, Statement st, ResultSet rs) { closeRs(rs); closeSt(st); closeConn(conn); } public static void release(Connection conn, Statement st) { closeSt(st); closeConn(conn); } private static void closeRs(ResultSet rs) { try { if(rs != null) { rs.close(); } rs = null; } catch (Exception e) { e.printStackTrace(); } finally { rs = null; } } private static void closeSt(Statement st) { try { if(st != null) { st.close(); } st = null; } catch (Exception e) { e.printStackTrace(); } finally { st = null; } } private static void closeConn(Connection conn) { try { if(conn != null) { conn.close(); } conn = null; } catch (Exception e) { e.printStackTrace(); } finally { conn = null; } } }
将增删改查等操作封装为接口。
标签:rac jdbcutil util 类加载 static creat set 分享 nts
原文地址:https://www.cnblogs.com/wbyixx/p/9648273.html