【电信计费系统项目实战】基础篇---jdbc连接数据库代码

    xiaoxiao2025-06-19  6

    此项目使用jdbc连接数据库的,既然连接数据库,肯定需要配置一些参数了,这里我们把这些参数配置在db.properties文件中(我电脑上没安装oracle,我换成了mysql)

    user=root password=wb url=jdbc:mysql://localhost:3306/test driver=com.mysql.jdbc.Driver #user=lihh #password=lihh2013 #url=jdbc:oracle:thin:@192.168.0.26:1521:tarena #driver=oracle.jdbc.OracleDriver

    那么来回顾一下jdbc连接数据库的操作步骤,先看它的核心代码:

    import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class DBUtil { private static String user; private static String password; private static String url; private static String driver; private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); static { Properties p = new Properties(); try { p.load(DBUtil.class.getClassLoader() .getResourceAsStream("db.properties")); user = p.getProperty("user"); password = p.getProperty("password"); url = p.getProperty("url"); driver = p.getProperty("driver"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "读取数据库配置文件失败!", e); } } public static Connection getConnection() { Connection con = tl.get(); if(con == null) { try { con = DriverManager.getConnection( url, user, password); tl.set(con); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException( "获取数据库连接失败!",e); } } return con; } public static void closeConnection() { Connection con = tl.get(); if(con != null) { try { con.close(); tl.set(null); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException( "关闭连接失败!",e); } } } public static void main(String[] args) { System.out.println(getConnection()); closeConnection(); } }

    根据上面的代码,总结一下jdbc连接数据库的步骤:

    1. 加载JDBC驱动程序

    加载数据库配置文件,加载驱动类,如

    p.load(DBUtil.class.getClassLoader() .getResourceAsStream("db.properties")); user = p.getProperty("user"); password = p.getProperty("password"); url = p.getProperty("url"); driver = p.getProperty("driver"); Class.forName(driver); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "读取数据库配置文件失败!", e); }

    补充:代码中的class.getClassLoader().getResourceAsStream(“db.properties”)是通过ClassLoader.getResourceAsStream这种方式加载properties文件的,这里顺便提一下Class.getResourceAsStream与ClassLoader.getResourceAsStream的区别:

    Class.getResourceAsStream(String path) : path 不以’/’开头时默认是从此类所在的包下取资源,以’/’开头则是从ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由 ClassLoader获取资源

    Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/’开头,最终是由ClassLoader获取资源

    2.提供JDBC连接的URL

    url=jdbc:mysql://localhost:3306/test mysql的格式为:jdbc:mysql: //ip:port/数据库名

    3.创建数据库的连接

    •要连接数据库,需要向java.sql.DriverManager请求并获得Connection对象, 该对象就代表一个数据库的连接。 •使用DriverManager的getConnectin(String url , String username , String password )方法传入指定欲连接的数据库的路径、数据库的用户名和密码来获得。

    public static Connection getConnection() { Connection con = tl.get(); if(con == null) { try { con = DriverManager.getConnection( url, user, password); tl.set(con); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException( "获取数据库连接失败!",e); } } return con; }

    4.创建一个Statement

    要执行SQL语句,必须获得java.sql.Statement实例,Statement实例分为以下3 种类型: 1、执行静态SQL语句。通常通过Statement实例实现。 2、执行动态SQL语句。通常通过PreparedStatement实例实现。 3、执行数据库存储过程。通常通过CallableStatement实例实现。

    5.执行SQL语句

    Statement接口提供了三种执行SQL语句的方法:executeQuery 、executeUpdate 和execute 1、ResultSet executeQuery(String sqlString):执行查询数据库的SQL语句 ,返回一个结果集(ResultSet)对象。 2、int executeUpdate(String sqlString):用于执行INSERT、UPDATE或 DELETE语句以及SQL DDL语句,如:CREATE TABLE和DROP TABLE等 3、execute(sqlString):用于执行返回多个结果集、多个更新计数或二者组合的 语句。

    6.处理结果

    两种情况: 1、执行更新返回的是本次操作影响到的记录数。 2、执行查询返回的结果是一个ResultSet对象。 • ResultSet包含符合SQL语句中条件的所有行,并且它通过一套get方法提供了对这些 行中数据的访问。 • 使用结果集(ResultSet)对象的访问方法获取数据: while(rs.next()){ String name = rs.getString(“name”) ; String pass = rs.getString(1) ; // 此方法比较高效 } (列是从左到右编号的,并且从列1开始)

    7.关闭JDBC对象

    操作完成以后要把所有使用的JDBC对象全都关闭,以释放JDBC资源,关闭顺序和声 明顺序相反: 1、关闭记录集 2、关闭声明 3、关闭连接对象

    以上步骤4,5,6,7的代码可参考查询资费的代码:

    public List<Cost> findAll() throws DAOException { List<Cost> list = new ArrayList<Cost>(); Connection con = DBUtil.getConnection(); String sql = "select * from cost"; try { PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while(rs.next()) { Cost c = createCost(rs); list.add(c); } } catch (SQLException e) { e.printStackTrace(); throw new DAOException( "查询全部的资费数据失败!", e); } finally { DBUtil.closeConnection(); } return list; }
    转载请注明原文地址: https://ju.6miu.com/read-1300102.html
    最新回复(0)