Java 数据库简单操作类
数据库操作类,将所有连接数据库的配置信息以及基本的CRUD操作封装在一个类里,方便项目里使用,将连接数据库的基本信息放在配置文件 "dbinfo.properties" 中,通过类加载器调用(也可以通过ServletContext调用配置文件,或者配置在web.xml里通过ServletConfig调用),需要修改数据库连接信息时,只需修改配置文件即可。
package com.latiny.db; import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties; /*
* 数据库操作类
*/ public class DBUtil { //定义需要的变量
private static String driver =null;
private static String url =null;
private static String user=null;
private static String password=null; private static Connection conn;
//使用PreparedStatment可以防止sql注入
private static PreparedStatement ps;
private static ResultSet rs;
private static CallableStatement cs; //读配置文件
private static Properties pp=null;
private static InputStream fis=null; //加载驱动,只需要执行一次
static
{
try
{
pp = new Properties(); //当我们使用java web的时候,读取文件要使用类加载器
fis = DBUtil.class.getClassLoader().getResourceAsStream("dbinfo.properties"); pp.load(fis);
driver = pp.getProperty("DRIVER");
url = pp.getProperty("URL");
user = pp.getProperty("USER");
password = pp.getProperty("PASSWORD"); // 1 加载驱动
Class.forName(driver); }
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fis = null;
}
} /*
* 获取Connection连接
*/
public static Connection getConn()
{
try
{
// 2 获取数据库连接
conn = DriverManager.getConnection(url, user, password);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} return conn;
} /*
* 直接返回rs结果,此方法不能关闭rs,因为后面调用它的类还会用到,如果关闭则不能正常使用
*/
public static ResultSet queryResult(String sql, String[] parameters)
{
try
{
conn = getConn();
// 3 创建Statement对象
ps = conn.prepareStatement(sql);
// 4 给问号赋值,即给sql语句的条件参数赋值如果需要的话
if(parameters!=null)
{
for(int i=1; i<=parameters.length; i++)
{
ps.setString(i, parameters[i-1]);
}
} // 5 执行sql获取返回结果
rs = ps.executeQuery();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} return rs;
} /*
* 将rs结果封装成ArrayList,然后可以关闭rs,节省数据库访问资源
*/
public static ArrayList queryResult2(String sql, String[] parameters)
{
ArrayList al = new ArrayList(); try
{
//2 获取数据库连接
conn = getConn();
//3 创建Statement对象
ps = conn.prepareStatement(sql);
//4 给问号赋值,即给sql语句的条件参数赋值如果需要的话
if(parameters!=null)
{
for(int i=1; i<=parameters.length; i++)
{
ps.setString(i, parameters[i-1]);
}
} //5 执行sql语句获取返回结果
rs = ps.executeQuery(); //获取rs的结构
ResultSetMetaData rsmd = rs.getMetaData();
//获取查询语句的列数
int column = rsmd.getColumnCount(); while(rs.next())
{
//对象数组,存储一行数据
Object[] objs = new Object[column];
for(int i=0; i<objs.length; i++)
{
objs[i] = rs.getObject(i+1);
}
al.add(objs);
} }
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//关闭资源
close(rs, ps, conn);
} return al;
} //调用存储过程,带输入输出参数的
public static CallableStatement callProcedure(String sql, String[] inputPara, Integer[] outputPara)
{ try
{
conn = getConn();
cs = conn.prepareCall(sql);
for(int i=0; inputPara!=null && i<inputPara.length; i++)
{
cs.setObject(i+1, inputPara[i]);
} //给output参数赋值
for(int j=0; outputPara!=null && j<outputPara.length; j++)
{
cs.registerOutParameter(inputPara.length+1+j, outputPara[j]);
} cs.execute(); } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
close(rs, ps, conn);
} return cs; } //update, insert, delete
public static Integer updateData(String sql, String[] parameters)
{
int result = 0;
try
{
conn = getConn();
ps = conn.prepareStatement(sql);
if(parameters!=null)
{
for(int i=0; i<parameters.length; i++)
{
ps.setObject(i+1, parameters[i]);
}
} //执行executeUpdate并且返回受影响的行数
result = ps.executeUpdate(); }
catch(Exception e)
{
e.printStackTrace();
}
finally
{
close(rs, ps, conn);
} return result;
} //关闭对应的数据库连接资源
public static void close(ResultSet rs1, PreparedStatement ps1, Connection conn1)
{ try
{
if(rs1!=null)
{
rs1.close();
}
if(ps1!=null)
{
ps1.close();
}
if(conn1!=null)
{
conn1.close();
} } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
dbinfo.properties文件配置信息
DRIVER=com.mysql.jdbc.Driver
URL=jdbc:mysql://localhost:3306/servlet
USER=latiny
PASSWORD=123456
Java 数据库简单操作类的更多相关文章
- Intellij IDEA集成mybatis-generator插件自动生成数据库实体操作类
Intellij IDEA集成mybatis-generator插件自动生成数据库实体操作类 转载至:https://blog.csdn.net/fishinhouse/article/details ...
- github上创建java项目简单操作
github上创建java项目简单操作 参考L: github上创建java项目简单操作 - CSDN博客http://blog.csdn.net/qq_29392425/article/detail ...
- SQL数据库简单操作
sql语言简介 (1)数据库是文件系统,使用标准sql对数据库进行操作 * 标准sql,在mysql里面使用语句,在oracle.db2都可以使用这个语句 (2)什么是sql * Structured ...
- [转]html5 js 访问 sqlite 数据库的操作类
本文转自:http://blog.csdn.net/tsxw24/article/details/7613815 webkit 核心的浏览器提供了 3个 api接口,用于访问本地sqlite数据,但使 ...
- java csv 文件 操作类
一个CSV文件操作类,功能比较齐全: package tool; import java.io.BufferedReader; import java.io.BufferedWriter; impor ...
- MongoDB数据库简单操作
之前学过的有mysql数据库,现在我们学习一种非关系型数据库 一.简介 MongoDB是一款强大.灵活.且易于扩展的通用型数据库 MongoDB 是由C++语言编写的,是一个基于分布式文件存储的开源数 ...
- fastCMS数据库相关操作类
fastCMS针对数据库的操作有以下几个类: 1.[paging_Class]分页类 此类用于分页检索数据库内符合条件的记录 1) 支持百万级数据分页 2) 支持多种类型的SQL语法,比如 Left ...
- sqlhelper 数据库帮助操作类
数据库帮助类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using S ...
- MySQL数据库简单操作
title date tags layout MySQL简单操作 2018-07-16 Linux post 登录mysql mysql -h 主机名 -u 用户名 -p 查看所有数据库 show d ...
随机推荐
- DBUtils温习1
1.简介 Commons DBUtIls是Apache组织提供的一个开源JDBC工具类库,它是对JDBC的简单封装,学习成本极低,但是使用DBUtils却极大的简化了dao层的开发,少些了很多的jdb ...
- 译文——The habits of highly successful people
1.Morning Routine (早上列行公事) Probably the most common habit ultra-successful people have is they can t ...
- MySQL高级知识(十五)——主从复制
前言:本章主要讲解MySQL主从复制的操作步骤.由于环境限制,主机使用Windows环境,从机使用用Linux环境.另外MySQL的版本最好一致,笔者采用的MySQL5.7.22版本,具体安装过程请查 ...
- MySQL高级知识(四)——Explain
前言:explain(执行计划),使用explain关键字可以模拟优化器执行sql查询语句,从而知道MySQL是如何处理sql语句.explain主要用于分析查询语句或表结构的性能瓶颈. 注:本系列随 ...
- 「APIO2017」商旅
「APIO2017」商旅 题目描述 在广阔的澳大利亚内陆地区长途跋涉后,你孤身一人带着一个背包来到了科巴.你被这个城市发达而美丽的市场所深深吸引,决定定居于此,做一个商人.科巴有 \(N\) 个集市, ...
- centos7下安装docker(15.8docker跨主机容器通信总结)
性能:underlay网络的性能优于overlay.Overlay网络利用隧道技术,将数据包封装到UDP中进行传输,由于涉及数据包的封装和解封,存在额外的CPU和网络的开销,虽然几乎所有overlay ...
- Python:margin collapse
margin collapse:边界 折叠/重叠/坍塌 此种现象只会垂直方向并且要满足一定条件时才会出现这种现象. https://tech.youzan.com/css-margin-collaps ...
- Python:Day05 作业
购物车: product_list = [['iphone6s',5800],['mac book',9800],['coffee',32],['book',80],['bike',1500]] sh ...
- APP耗电量测试
现象 APP耗电,导致电池续航能力不佳,如下图,在小米MIX2和iPhone X机型上后台静默一小时各应用的耗电排行: 基本概念 相对于PC来说,移动设备的电池电量是非常有限的,保持持久的续航能力尤为 ...
- P2257 YY的GCD--洛谷luogu
传送门 题目描述 神犇YY虐完数论后给傻×kAc出了一题 给定N, M,求1<=x<=N, 1<=y<=M且gcd(x, y)为质数的(x, y)有多少对 kAc这种傻×必然不 ...