时间:2021-07-01 10:21:17 帮助过:12人阅读
测试代码:
package edu.aeon.aeonutils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * [说明]:测试连接数据库工具类(version 1.2) * @author aeon * */ public class TestAeonJdbcUtils { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { connection = AeonJdbcUtils.getMySqlConnection(); statement = connection.createStatement(); String sql = "select * from user"; resultSet = statement.executeQuery(sql); System.out.println("用户id\t用户名\t用户密码"); while (resultSet.next()) { int userId = resultSet.getInt("userId");// 根据表字段名获取该行记录上的字段名所对应的字段值 String userName = resultSet.getString("userName"); String userPw = resultSet.getString("userpw");// 数据库中的字段不区分大小写 System.out.println(userId + "\t" + userName + "\t" + userPw); } } catch (ClassNotFoundException e) { System.out.println("加载驱动失败!"); e.printStackTrace(); } catch (SQLException e) { System.out.println("连接数据库失败!"); e.printStackTrace(); } AeonJdbcUtils.closeDB(resultSet, statement, connection); } }
database.properties中的配置信息:
username=root password=root driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/db_test
项目包视图截图如下:
建库及表语句:
drop database db_test; create database db_test; use db_test; create table user( userId int(5) primary key comment ‘用户id‘, userName varchar(16) comment ‘用户姓名‘, userPw varchar(16) comment ‘用户密码‘ ); insert into user(userId,userName,userPw) values(10001,‘user1‘,‘user1‘); insert into user(userId,userName,userPw) values(10002,‘user2‘,‘user2‘); insert into user(userId,userName,userPw) values(10003,‘user3‘,‘user3‘); insert into user(userId,userName,userPw) values(10004,‘user4‘,‘user4‘); insert into user(userId,userName,userPw) values(10005,‘user5‘,‘user5‘);
数据库信息截图:
测试结果截图:
dljd_011_jdbc再次封装工具类_把数据库的相关信息写到配置文件中,减低代码的耦合度
标签:tst 用户密码 9.png create 说明 NPU closed driver 加载