Java学习笔记48(DBUtils工具类一)
上一篇的例子可以明显看出,在增删改查的时候,很多的代码都是重复的,
那么,是否可以将增删改查封装成一个类,方便使用者
package demo; /*
* 实现JDBC的工具类
* 定义方法,直接返回数据库的连接对象
*
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class JDBCUtils {
private JDBCUtils() {
} private static Connection con; static {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mybase";
String username = "root";
String password = "xuyiqing";
con = DriverManager.getConnection(url, username, password);
} catch (Exception ex) {
throw new RuntimeException(ex + "数据库连接失败");
}
} /*
* 定义静态方法,返回数据库的连接对象
*/
public static Connection getConnection() {
return con;
} // 关闭方法
public static void close(Connection con, Statement stat) { if (stat != null) {
try {
stat.close();
} catch (SQLException ex) {
}
} if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
} } // 重载
public static void close(Connection con, Statement stat, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
}
} if (stat != null) {
try {
stat.close();
} catch (SQLException ex) {
}
} if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
} }
}
测试类:
package demo; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; public class TestJDBCUtils {
public static void main(String[] args) throws Exception {
Connection con = JDBCUtils.getConnection();
PreparedStatement pst = con.prepareStatement("SELECT sname FROM sort");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("sname"));
}
JDBCUtils.close(con, pst, rs);
}
}
可以将表中的数据储存到对象中:
package demo;
public class Sort {
private int sid;
private String sname;
private double sprice;
private String sdesc;
public Sort(int sid, String sname, double sprice, String sdesc) {
this.sid = sid;
this.sname = sname;
this.sprice = sprice;
this.sdesc = sdesc;
}
public Sort() {
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public double getSprice() {
return sprice;
}
public void setSprice(double sprice) {
this.sprice = sprice;
}
public String getSdesc() {
return sdesc;
}
public void setSdesc(String sdesc) {
this.sdesc = sdesc;
}
@Override
public String toString() {
return "Sort [sid=" + sid + ", sname=" + sname + ", sprice=" + sprice + ", sdesc=" + sdesc + "]";
}
}
package demo; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; /*
* JDBC读取数据表sort,每行数据封装到Sort类的对象中
* 很多个Sort类对象,存储到List集合中
*/
public class JDBCDemo {
public static void main(String[] args) throws Exception{
//使用JDBC工具类,直接获取数据库连接对象
Connection con = JDBCUtils.getConnection();
//连接获取数据库SQL语句执行者对象
PreparedStatement pst = con.prepareStatement("SELECT * FROM sort");
//调用查询方法,获取结果集
ResultSet rs = pst.executeQuery();
//创建集合对象
List<Sort> list = new ArrayList<Sort>();
while(rs.next()){
//获取到每个列数据,封装到Sort对象中
Sort s = new Sort(rs.getInt("sid"),rs.getString("sname"),rs.getDouble("sprice"),rs.getString("sdesc"));
//封装的Sort对象,存储到集合中
list.add(s);
}
JDBCUtils.close(con, pst, rs);
//遍历List集合
for(Sort s : list){
System.out.println(s);
}
}
}
这里有一个问题,我们自定义的工具类中的数据是不能修改的,那么如果要改变驱动、用户名、或是连接地址,很不方便
所以,可以把参数放在配置文件中,修改的时候只要改变配置文件即可,不需要修改源码,有利于后期维护
配置文件通常放在scr文件下
这里注意,在src目录下创建文件的时候在bin目录下也会自动复制这个文件
创建文件database.properties,写入键值对
diverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybase
username=root
password=xuyiqing
使用IO流加载配置文件:
package demo; import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties; public class PropertiesDemo {
public static void main(String[] args) throws Exception {
//以前的方法
//FileInputStream fis1 = new FileInputStream("database.properties");
//这里介绍新方法:类的加载器,从bin目录下加载
InputStream in = PropertiesDemo.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);
System.out.println(pro);
}
}
输出:{password=xuyiqing, url=jdbc:mysql://localhost:3306/mybase, diverClass=com.mysql.jdbc.Driver, username=root}
成功加载
于是想到是否可以通过配置文件连接数据库?
package demo; import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; public class JDBCUtils {
private JDBCUtils() {
} private static Connection con; static {
try {
InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro = new Properties();
pro.load(in);
String diverClass = pro.getProperty("driverClass");
String url = pro.getProperty("url");
String username = pro.getProperty("username");
String password = pro.getProperty("password");
Class.forName(diverClass);
con = DriverManager.getConnection(url, username, password);
} catch (Exception ex) {
throw new RuntimeException(ex + "数据库连接失败");
}
} public static Connection getConnection() {
return con;
} public static void close(Connection con, Statement stat) { if (stat != null) {
try {
stat.close();
} catch (SQLException ex) {
}
} if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
} } public static void close(Connection con, Statement stat, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
}
} if (stat != null) {
try {
stat.close();
} catch (SQLException ex) {
}
} if (con != null) {
try {
con.close();
} catch (SQLException ex) {
}
} }
}
Java学习笔记48(DBUtils工具类一)的更多相关文章
- Java学习笔记七——数组工具类Arrays
数组工具类Arrays Java提供的Arrays类里包含的一些static修饰的方法可以直接操作数组.若将里面的方法用熟的话,那开发效率会大大提高.下面介绍其中的方法. List<T> ...
- 并发编程学习笔记(10)----并发工具类CyclicBarrier、Semaphore和Exchanger类的使用和原理
在jdk中,为并发编程提供了CyclicBarrier(栅栏),CountDownLatch(闭锁),Semaphore(信号量),Exchanger(数据交换)等工具类,我们在前面的学习中已经学习并 ...
- java学习笔记07--日期操作类
java学习笔记07--日期操作类 一.Date类 在java.util包中定义了Date类,Date类本身使用非常简单,直接输出其实例化对象即可. public class T { public ...
- java学习笔记之日期日历类
java学习笔记之日期日历 Date日期类概述: 表示特定的瞬间,精确到毫秒 Date类的构造方法: 1.空参数构造方法 Date date = new Date(); 获取到当前操作系统中的时间和日 ...
- Java学习笔记26(Math类、Arrays类、BigInteger类、BigDecimal类)
Math类:数学工具类,做一些数学计算,开方,对数,三角函数等 所有方法都是静态方法,不需要建立对象,直接用类名调用即可 示例: 这里写几个在日常开发中会用到的,比如三角函数之类的平时不会用到,了解即 ...
- java学习-加载.properties工具类
javaWeb项目,要加载xxx.properties或其它如.txt, .md后缀的文本文件 文本内容有两种格式 key:value或者key=value 诸如Spring框架,Jfinal框架,都 ...
- [Guava学习笔记]Collections: 集合工具类
我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3861431.html,享受整齐的排版.有效的链接.正确的代码缩进.更好的阅读体验 ...
- 吴裕雄--天生自然java开发常用类库学习笔记:集合工具类Collections
import java.util.Collections ; import java.util.List ; import java.util.Set ; public class Collectio ...
- Java学习笔记20(String类应用、StringBuffer类、StringBuilder类)
1.获取指定字符串中大小写和数字的个数: package demo; public class StringTest { public static void main(String[] args) ...
随机推荐
- mybatis泛型(一)
mybatis的确很方便,可以随意配置sql语句,并根据参数生成指定的sql,也可以根据查询结果生成指定对象 但是有一点非常恐怖,就是每个数据库表都必须有一个配置,等于在一个系统里做了很多重复的工作, ...
- 吴裕雄 python深度学习与实践(10)
import tensorflow as tf input1 = tf.constant(1) print(input1) input2 = tf.Variable(2,tf.int32) print ...
- 最流行的Python编辑器/IDEs你认识吗?
来源商业新知网,原标题:来!带你认识几种最流行的Python编辑器/IDEs(附链接) 大数据文摘授权转载自数据派THU 作者:By Gregory Piatetsky 格雷戈里·皮亚特斯基,KDnu ...
- WordCount 3
学号:201631062130.201631062304 码云地址:https://gitee.com/xnsy/WordCountPlus 一.代码互审情况:在代码的互审过程中,在命令和路径没有没有 ...
- HDU2665 求区间第K大 主席树
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=2665 代码: //#include<bits/stdc++.h> #include< ...
- azkaban 执行hive语句
#hivef.jobtype=commandcommand=hive -f test.sql #test.sql use default;drop table aztest;create table ...
- 安全运维之:Linux后门入侵检测工具的使用
安全运维之:Linux后门入侵检测工具的使用 https://blog.csdn.net/exitgogo/article/details/39547113
- 426. Convert Binary Search Tree to Sorted Doubly Linked List把bst变成双向链表
[抄题]: Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right po ...
- PHP导出Excel表
<?php/** * Created by PhpStorm. * User: admin * Date: 2019/3/16 * Time: 9:41 *///利用excel导出插件PHPEx ...
- Fabric的权限管理:Attribute-Based Access Control
之前稍微了解过Client Identity Chaincode Library,这几天正好开始实际应用. 虽然了解过,还是发现了不少之前理解的不足,也踩了不少坑. 先列出官方介绍: https:// ...