一个JDBC工具类

阅读: 评论:0

一个JDBC工具类

一个JDBC工具类

一个JDBC工具类

    • 前言
    • JDBCUtils.java
    • 配置文件
    • 使用实例

前言

在使用Java操作MySQL数据库的时候,会使用到JDBC驱动,但是在每次连接并使时都需要创建一堆的类和相关参数,还是有点麻烦的。在这里有一个封装好的JDBC工具类,里面包含了Java连接MySQL数据库时所需要的的属性和方法,代码如下。

JDBCUtils.java

/*** 对JDBC进行封装的工具类* 完成MySQL的连接和资源关闭*/
public class JDBCUtils {//定义相关的连接属性private static String user;//用户名private static String password;//密码private static String url;//urlprivate static String driver;//驱动名//在static代码块进行初始化static {Properties properties = new Properties();try {properties.load(new FileInputStream("src\mysql.properties"));//改路径是配置文件的路径//读取相关的属性值user = Property("user");//获取用户名password = Property("password");//获取密码url = Property("url");//获取连接URLdriver = Property("driver");//获取驱动的路径} catch (IOException e) {//在实际开发中,可以这样处理IOException//编译异常-->运行处理//调用者可以选择捕获该异常,也可以选择默认处理,比较方便throw new RuntimeException(e);}}//编写方法,连接数据库,返回Connection给使用工具类的程序public static Connection getConnection(){try {Connection(url,user,password);} catch (SQLException e) {throw new RuntimeException(e);}}//关闭相关资源/*** ResultSet 结果集* Statement 或 PreparedStatement* Connection* 如果需要关闭资源,就传入对象,否则传入null*/public static  void close(ResultSet set, Statement statement,Connection connection){//判断是否为空try {if (set != null){set.close();}if (statement != null){statement.close();}if (connection != null){connection.close();}} catch (SQLException e) {throw new RuntimeException(e);}}
}

配置文件

注意:配置文件的 " = " 两边不能有空格

user=数据库用户名
password=密码
url=jdbc:mysql://localhost:3306/test
driver&#sql.jdbc.Driver

使用实例

/*** 使用JDBCUtils工具类*/
public class JDBCUtils_Use {public static void main(String[] args) {//得到一个连接对象Connection connection = Connection();//组织一个SQL语句// String sql = "update admin set name = ? where id = ?";String sql1 = "select * from `admin`";PreparedStatement preparedStatement = null;//扩大作用域ResultSet set = null;//创建一个PreparedStatement对象try {preparedStatement = connection.prepareStatement(sql1);//给占位符赋值
//            preparedStatement.setString(1,"张三");
//            preparedStatement.setInt(2,1);//开始执行SQL语句int rows = uteUpdate();//这里的会返回一个受影响行数的int值,在JDBC中,使用不同的 preparedStatement 的方法,会有不同的返回值,比如下面的 executeQuery() 方法是一个返回一个结果集,可以通过遍历的方法将结果集的内容打印出来。set = uteQuery();
//            System.out.println(rows+" 行受到影响");//得到结果集//遍历该结果集while (()){int id = Int("id");String name = String("name");System.out.println(id +"t"+ name);}} catch (SQLException e) {e.printStackTrace();} finally {//关闭资源JDBCUtils.close(set,preparedStatement,connection);}}
}

本文发布于:2024-02-02 23:11:51,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170688671247076.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:工具   JDBC
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23