JDBC连接数据库方法的封装,以及查询数据方法的封装
(在上一篇文章中,我们详细的介绍了连接数据库的方法,以及eclipse操作数据库信息的相关方法,在这里我们将主要讲封装。)
主要内容:
- 一般的连接数据库测试
- 把连接数据库的方法封装成一个类和测试
- 一个简单的插入表实例
- 查询数据实例
- 封装查询的数据库的信息
- 封装信息后的查询数据库
一.一般的数据库连接测试
public class TestConnection1 {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/test?"//数据库url
+ "useUnicode=true&characterEncoding=UTF8";//防止乱码
String user="h4";
String pass="111";
Connection conn=DriverManager.getConnection(url, user, pass);
System.out.println(conn+",成功连接数据库");
conn.close();
}
}
二.我们不可能每写一个处理信息功能就写一次连接,这样太麻烦,那么为了方便以后的应用,我们通常把数据库连接封装起来。
具体实现步骤如下:
1.定义变量:
private static String DRIVER_CLASS;
private static String URL;
private static String USERRNAME;
private static String PASSWORD;
2.在你建的eclipse根目录下新建一个File文件Properties;
文件内容为你定义的变量所指向的对象:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test? useUnicode=true&characterEncoding=UTF8
user=h4
pass=111
3.构建一个Properties对象:Properties p=new Properties();
4. java.io下的类FileInputStream的方法;FileInputStream(String name) :通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。
来获取这个文件里面的资料:FileInputStream fis=new FileInputStream("db.properties");
5. 用3构建的变量p来下载资料:p.load(fis);
6.利用getProperty();获取参数:
DRIVER_CLASS=p.getProperty("driver");
URL=p.getProperty("url");
USERRNAME=p.getProperty("user");
PASSWORD=p.getProperty("pass");
7.写一个连接数据库的方法getConection();
8.写一个关闭数据库的方法close(Connection conn);
写好后代码如下:
public class jdbcutil {
private static String DRIVER_CLASS;
private static String URL;
private static String USERRNAME;
private static String PASSWORD;
private static Properties p=new Properties();
static{
try {
FileInputStream fis=new FileInputStream("db.properties");
p.load(fis);
DRIVER_CLASS=p.getProperty("driver");
URL=p.getProperty("url");
USERRNAME=p.getProperty("user");
PASSWORD=p.getProperty("pass");
Class.forName(DRIVER_CLASS);
fis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConection(){
Connection conn=null;
try{
conn=DriverManager.getConnection(URL, USERRNAME, PASSWORD);
}
catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn) {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
那么封装好之后,我们来写一个测试类,测试连接
public class TestConnection2 {
public static void main(String[] args) throws Exception {
Connection conn=jdbcutil.getConection();//利用封装好的类名来调用连接方法便可
System.out.println(conn+",成功连接数据库");
jdbcutil.close( conn);//同样利用类名调用关闭方法即可
}
}
三.连接成功,我们写一个简单的向数据库插入表的实例。
public class TestDDl {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
conn=jdbcutil.getConection();//连接数据库
String createTableSql= " create table user_test1( "+//记住引号和单词间一定要有空格
" id int, "+
" name varchar(32) , "+
" password varchar(32) , "+
" birthday date "+
" ) ";
try {
stmt=conn.createStatement();
stmt.execute(createTableSql);
} catch (SQLException e) {
e.printStackTrace();
}
jdbcutil.close(null, stmt, conn);//关闭数据库
}
}
四.我们在写一个查询数据库数据的实例。(有三种方法)
public class TestDQL {
public static void main(String[] args){
Connection conn=null;//定义为空值
Statement stmt=null;
ResultSet rs=null;
String sql="select * from employees";//sql语句
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();//创建一个Statement语句对象
rs=stmt.executeQuery(sql);//执行sql语句
while(rs.next()){
System.out.print(rs.getInt(1)+",");
System.out.print(rs.getString(2)+",");//直接使用参数
System.out.print(rs.getString(3)+",");
System.out.print(rs.getString(4)+",");
System.out.println(rs.getString(5));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);//关闭数据库
}
}
}
//第二种方法如下:
public class TestDQl2 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String sql="select * from employees";
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt("userid")+",");//里面直接写要查找的内容名称
System.out.print(rs.getString("employee_id")+",");
System.out.print(rs.getString("last_name")+",");
System.out.print(rs.getString("salary")+",");
System.out.println(rs.getString("department_id"));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
}
}
//第三种方法如下:
public class TestDQL3 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String sql="select * from employees";
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){
int index=1;
System.out.print(rs.getInt(index++)+",");
System.out.print(rs.getString(index++)+",");
System.out.print(rs.getString(index++)+",");
System.out.print(rs.getString(index++)+",");
System.out.println(rs.getString(index++));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
}
}
五.在四里面我们写了查询员工资料的信息,但是有的时候我们要保存起来方便之后更好的查找,那怎么办呢?没错,封装。
public class employees implements Serializable {
private Integer userid;
private String employee_id;
private String last_name;
private String salary;
private String department_id;
public employees() {
super();
}
public employees(String employee_id, String last_name, String salary, String department_id) {
super();
this.employee_id = employee_id;
this.last_name = last_name;
this.salary = salary;
this.department_id = department_id;
}
@Override
public String toString() {
return "employees [userid=" + userid + ", employee_id=" + employee_id + ", last_name=" + last_name
+ ", salary=" + salary + ", department_id=" + department_id + "]";
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getEmployee_id() {
return employee_id;
}
public void setEmployee_id(String employee_id) {
this.employee_id = employee_id;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getSalary() {
return salary;
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getDepartment_id() {
return department_id;
}
public void setDepartment_id(String department_id) {
this.department_id = department_id;
}
}
六.封装好后的查询和上面没封装之前有点变化。
public class TestDQL4 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
List<employees> emps=new ArrayList<>();//构造集合对象
String sql="select * from employees";
conn=jdbcutil.getConection();//获取数据库连接
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){//遍历结果集
int index=1;
employees emp=new employees();//构造员工类对象
emp.setUserid(rs.getInt(index++));//获取值
emp.setEmployee_id(rs.getString(index++));
emp.setLast_name(rs.getString(index++));
emp.setSalary(rs.getString(index++));
emp.setDepartment_id(rs.getString(index++));
emps.add(emp);//放到集合中去
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);//关闭连接
}
for(employees emp:emps){//遍历
System.out.println(emp);
}
}
}
其实我们可以继续封装,把遍历结果集给封装起来。
public class TestDQL5 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
List<employees> emps=new ArrayList<>();
String sql="select * from employees";
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
emps=resultSetToEmployees(rs);
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
for(employees emp:emps){
System.out.println(emp);
}
}
public static List<employees> resultSetToEmployees(ResultSet rs){
List<employees> emps=new ArrayList<>();
try {
while(rs.next()){
int index=1;
employees emp=new employees();
emp.setUserid(rs.getInt(index++));
emp.setEmployee_id(rs.getString(index++));
emp.setLast_name(rs.getString(index++));
emp.setSalary(rs.getString(index++));
emp.setDepartment_id(rs.getString(index++));
emps.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
}
return emps;
}
}
如果是一个人查询信息呢?还可以这样封装。
public class TestDQL6 {
public static void main(String[] args) {
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
List<employees> emps=new ArrayList<>();
String sql="select * from employees";
conn=jdbcutil.getConection();
try {
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
while(rs.next()){
employees emp=resultSetToEmployee(rs);
emps.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
jdbcutil.close(rs,stmt,conn);
}
for(employees emp:emps){
System.out.println(emp);
}
}
public static employees resultSetToEmployee(ResultSet rs){
employees emp=null;
try {
int index=1;
emp=new employees();
emp.setUserid(rs.getInt(index++));
emp.setEmployee_id(rs.getString(index++));
emp.setLast_name(rs.getString(index++));
emp.setSalary(rs.getString(index++));
emp.setDepartment_id(rs.getString(index++));
} catch (SQLException e) {
e.printStackTrace();
}
return emp;
}
}
JDBC连接数据库方法的封装,以及查询数据方法的封装的更多相关文章
- Java学习-029-JSON 之三 -- 模仿 cssSelector 封装读取 JSON 数据方法
前文简单介绍了如何通过 json-20141113.jar 提供的功能获取 JSON 的数据,敬请参阅:Java学习-028-JSON 之二 -- 数据读取. 了解学习过 JQuery 的朋友都知道, ...
- Hibernate原生SQL查询数据转换为HQL查询数据方法
HQL形式:(构造方法不支持timestamp类型) public List<Device> queryByMatherBoardId(String matherBoardId) { St ...
- Spring查询方法的注入 为查询的方法注入某个实例
//这里是客户端的代码 当调用CreatePersonDao这个抽象方法或者虚方法的时候由配置文件返回指定的实例 为查询的方法注入某个实例 start static void Main(string[ ...
- SpringBoot JDBC 源码分析之——NamedParameterJdbcTemplate 查询数据返回bean对象
1,NamedParameterJdbcTemplate 查询列表 /***测试***/ public void queyBeanTest(){ String s = "select * f ...
- Sqlite数据库添加数据以及查询数据方法
只是两个添加查询方法而已,怕时间长不用忘了
- 用python实现数据库查询数据方法
哈喽,好久没来了,最近搞自动化发现了很多代码弯路,特别分享出来给能用到的朋友 因为公司业务的关系,每做一笔功能冒烟测试,我们就要对很多的数据库表中的字段进行校验,当时我就想反正总是要重复的运行这些SQ ...
- JDBC查询数据实例
在本教程将演示如何在JDBC应用程序中,查询数据库的一个表中数据记录. 在执行以下示例之前,请确保您已经准备好以下操作: 具有数据库管理员权限,以在给定模式中数据库表中查询数据记录. 要执行以下示例, ...
- SSH框架的多表查询(方法二)增删查改
必须声明本文章==>http://www.cnblogs.com/zhu520/p/7773133.html 一:在前一个方法(http://www.cnblogs.com/zhu520/p ...
- SSH框架的多表查询(方法二)
必须声明本文章==>http://www.cnblogs.com/zhu520/p/7773133.html 一:在前一个方法(http://www.cnblogs.com/zhu520/p ...
随机推荐
- Service与BoardcastReceive
开发service需要两个步骤: 1.定义一个继承Service的子类 2.在AndroidMainfest.xml文件中配置该Service. Service与Activity都是从Context派 ...
- CF1067D. Computer Game(斜率优化+倍增+矩阵乘法)
题目链接 https://codeforces.com/contest/1067/problem/D 题解 首先,如果我们获得了一次升级机会,我们一定希望升级 \(b_i \times p_i\) 最 ...
- sql count中加条件
一般的,我们会在where, 或者 having中加条件,count中只是某个字段 今天看到另外一种写法,不知道性能怎么样 select count( case when xxx>10 and ...
- Jenkins 发布平台 MSB4064: The "Retries" parameter is not supported & error MSB4063: The "Copy" task could not be initialized
____________________________________________________________________________________________________ ...
- URL中参数为数组
今天写代码时候碰到了一个需要在URL中传递数组类型的参数,记录一下. var urlstr = "http://test"; var test = new Array(); for ...
- lfs
LFS──Linux from Scratch,就是一种从网上直接下载源码,从头编译LINUX的安装方式.它不是发行版,只是一个菜谱,告诉你到哪里去买菜(下载源码),怎么把这些生东西( raw c ...
- Ubuntu 18.04上搭建FTP服务器
1.准备工作需要安装并运行的Ubuntu Server 18.04系统.当然还需要一个具有sudo权限的账号. 2.安装VSFTPVSFTP程序位于标准存储库中,因此可以使用单个命令删除安装.打开终端 ...
- Mac下配置maven和集成到ecclipse(Mac 10.12)
1.到官网下载maven,http://maven.apache.org/download.cgi 下载好的tar.gz包解压出来,并重命名为maven3,拷贝到/usr/local目录下 2.配置环 ...
- 【javascript/css】关于鼠标事件onmousexxx和css伪类hover
在运用鼠标移入移出事件时,一般有两种做法,一种是DOM事件的"onmouseover"和"onmouseout",还有一种是css的伪类":hover ...
- poj 3750 小孩报数问题
小孩报数问题 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 11527 Accepted: 5293 Descripti ...