java sqlite 工具类_Java 工具类 - JDBC通用操作基类 BaseDao
封装了增删改查功能
适用于MySQL、Oracle、SQLServer、DB2、Sybase、JTDS、PostgreSql、SQLite、Derby、H2、HSQLDB、ODBC 等等数据库,有需要的还可以自己增加。
package com.tgb.hz.jdbc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* 数据访问基类
* 支持 MySQL、Oracle、SQLServer、DB2、Sybase、PostgreSql、SQLite、Derby、H2、HSQLDB、ODBC、SQLServer_JTDS、Sybase_JTDS
*
切换数据库时,需要指定相关参数
*
* @author hezhao
* @Time 2017年7月27日 下午4:22:23
* @Description 无
* @Version V 1.0
*/
public class BaseDao {
private final Logger logger = LoggerFactory.getLogger(BaseDao.class);
private final boolean isLog = false;//是否记录SQL日志
private final boolean isConfig = false;//是否需要配置文件
private final boolean isDataSource = false;//是否从连接池取连接
private final String datasource = "";//如果是从连接池取连接,那么给出连接名称
private final DBType type = DBType.MySQL;//数据库类型
// 数据库名
private final String db = "dbname";
private final String ip = "127.0.0.1";
private String name = "root";
private String pwd = "root";
private String driver;
private String url;
private Connection conn = null;
private PreparedStatement pstmt = null;
protected ResultSet rs = null;
{
//把JDBC配置信息放在配置文件中
if(isConfig){
final Properties properties = new Properties();
try {
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
} catch (final IOException e) {
logger.error("加载JDBC配置信息失败...");
logger.error(e.toString(),e);
}
driver = properties.getProperty("jdbc.driver");
url = properties.getProperty("jdbc.url");
name = properties.getProperty("jdbc.username");
pwd = properties.getProperty("jdbc.password");
}else{
if(type == DBType.MySQL){
driver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://"+ip+":3306/"+db+"?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
}else if(type == DBType.SQLServer){
//1、使用sqljdbc
driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
url = "jdbc:sqlserver://"+ip+":1433;DatabaseName="+db;
}else if(type == DBType.SQLServer_JTDS){
//2、使用jtds
driver = "net.sourceforge.jtds.jdbc.Driver";
url = "jdbc:jtds:sqlserver://"+ip+":1433;DatabaseName="+db;
}else if(type == DBType.Oracle){
driver = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@"+ip+":1521:"+db;
}else if(type == DBType.DB2){
driver = "com.ibm.db2.jcc.DB2Driver";
url = "jdbc:db2://"+ip+":50000/"+db;
}else if(type == DBType.Sybase){
driver = "com.sybase.jdbc.SybDriver";
url = "jdbc:sybase:Tds:"+ip+":5007/"+db;
}else if(type == DBType.Sybase_JTDS){
driver = "net.sourceforge.jtds.jdbc.Driver";
url = "jdbc:jtds:sybase://"+ip+":5007/"+db;
}else if(type == DBType.PostgreSql){
driver = "org.postgresql.Driver";
url = "jdbc:postgresql://"+ip+"/"+db;
}else if(type == DBType.SQLite){
driver = "org.sqlite.JDBC";
url = "jdbc:sqlite:"+db;//jdbc:sqlite:person.db
}else if(type == DBType.H2){
driver = "org.h2.Driver";
url = "jdbc:h2:tcp://"+ip+"/~/"+db;
}else if(type == DBType.HSQLDB){
driver = "org.hsqldb.jdbcDriver";
url = "jdbc:hsqldb:hsql://"+ip+":9001/"+db;
}else if(type == DBType.Derby){
driver = "org.apache.derby.jdbc.ClientDriver";
url = "jdbc:derby://"+ip+":1527/"+db+";";
}else if(type == DBType.ODBC){
driver = "sun.jdbc.odbc.JdbcOdbcDriver";
url = "jdbc:odbc:"+db;
}
}
}
private void getConnection() {
if(!isDataSource){
//1、通过JDBC获得链接
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, name, pwd);
} catch (Exception e) {
logger.error(e.toString(),e);
}
}else{
//2、通过数据连接池获得链接
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup(datasource);
this.conn = ds.getConnection();
} catch (NamingException e) {
logger.error(e.toString(),e);
} catch (SQLException e) {
logger.error(e.toString(),e);
}
}
}
/**
* 关闭资源
*/
protected void closeAll() {
try {
if (this.rs != null) {
rs.close();
}
if (this.pstmt != null) {
pstmt.close();
}
if (this.conn != null) {
conn.close();
}
} catch (SQLException e) {
logger.error(e.toString(),e);
}
}
/**
* 增删改通用
* @author hezhao
* @Time 2017年7月27日 下午4:22:09
* @Description 无
* @Version V 1.0
* @param sql
* @param prams
* @return
*/
protected int executeUpdate(String sql, Object... prams) {
try {
this.getConnection();
this.pstmt = conn.prepareStatement(sql);
if (prams != null) {
for (int i = 0; i < prams.length; i++) {
this.pstmt.setObject(i + 1, prams[i]);
}
}
log(sql, prams);
return this.pstmt.executeUpdate();
} catch (SQLException e) {
logger.error(e.toString(),e);
} finally {
closeAll();
}
return 0;
}
/**
* 新增,返回主键
* @author hezhao
* @Time 2017年1月18日 下午2:23:07
* @param sql
* @param prams
* @return
*/
protected int executeInsert(String sql, Object... prams) {
try {
this.getConnection();
//传入参数:STATEMENT.RETURN_GENERATED_KEYS,指定返回生成的主键
this.pstmt = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
if (prams != null) {
for (int i = 0; i < prams.length; i++) {
this.pstmt.setObject(i + 1, prams[i]);
}
}
log(sql, prams);
//执行sql
int count = this.pstmt.executeUpdate();
//返回的主键
int autoIncKey = 0;
if(count > 0){
ResultSet rs = pstmt.getGeneratedKeys(); //获取结果
if (rs.next()) {
autoIncKey = rs.getInt(1);//取得ID
} else {
// throw an exception from here
logger.error("插入语句出错,没有获取到新增的ID!");
}
}
return autoIncKey;
} catch (SQLException e) {
logger.error(e.toString(),e);
} finally {
closeAll();
}
return 0;
}
/**
* 查询通用
* @author hezhao
* @Time 2017年7月27日 下午4:22:45
* @Description 无
* @Version V 1.0
* @param sql
* @param prams
*/
protected void executeQuery(String sql, Object... prams) {
try {
this.getConnection();
this.pstmt = conn.prepareStatement(sql);
if (prams != null) {
for (int i = 0; i < prams.length; i++) {
this.pstmt.setObject(i + 1, prams[i]);
}
}
log(sql, prams);
this.rs = this.pstmt.executeQuery();
} catch (SQLException e) {
logger.error(e.toString(),e);
}
}
/**
* 打印日志
* @author hezhao
* @Time 2017年7月27日 下午4:22:56
* @Description 无
* @Version V 1.0
* @param sql
* @param prams
*/
private void log(String sql, Object[] prams) {
if(isLog) {
System.out.println("===========" + sql);
if (prams != null && prams.length > 0) {
System.out.println("参数:");
for (int i = 0; i < prams.length; i++) {
if (i == prams.length - 1) {
System.out.print(prams[i] + "\n");
} else {
System.out.print(prams[i] + ",");
}
}
}
}
}
/**
* 数据库类型
* @author hezhao on 2017年7月27日 上午11:26:08
*
*/
static enum DBType{
MySQL,
Oracle,
SQLServer,//SQLServer2005
SQLServer_JTDS,//使用jtds连接SQLServer
DB2,
Sybase,
Sybase_JTDS,//使用jtds连接Sybase
PostgreSql,
SQLite,
Derby,
H2,
HSQLDB,
ODBC;//桥连接
}
}
java sqlite 工具类_Java 工具类 - JDBC通用操作基类 BaseDao相关推荐
- mysql 操作类 C .net_.NET MYSQL数据库操作基类( C#源码)
使用MySql.Data.dll,它.Net访问MySQL数据库的一个驱动 下载 DbHelperMySql.CS using System; using System.Collections; us ...
- java 单例基类_PHP基于单例模式实现的数据库操作基类
本文实例讲述了PHP基于单例模式实现的数据库操作基类.分享给大家供大家参考,具体如下: 配置文件: $db = array( 'host'=>'localhost', 'user'=>'r ...
- BIM工程信息管理系统-EF实体框架数据操作基类
EF实体框架数据操作基类主要是规范增.改.查.分页.Lambda表达式条件处理,以及异步操作等特性,这样能够尽可能的符合基类这个特殊类的定义,实现功能接口的最大化重用和统一. 1.程序代码 /// & ...
- 写出一个类People,并由该类做基类派生出子类Employee和Teacher
写出一个类People,并由该类做基类派生出子类Employee和Teacher.其中People 类具有name.age两个保护成员变量,分别为String类型.整型,且具有公有的getAge成员函 ...
- 虚基类、虚函数和纯虚基类
http://blog.csdn.net/lovemysea/article/details/5298589 首先看一个例子: class Base { public: virtual voi ...
- java 输出一个爱心_java基础 之 几个常用的类
在以上的文章中我们看了Java的一些基础的使用,今天我们主要学习一下Java的几个常用的类 java操作系统底层Sytem类: System类代表当前Java程序的运行平台,程序不能创建System类 ...
- java函数修饰符_Java 函数 面向对象,修饰符,类,构造方法,this
1.函数 函数就是定义在类中,具有特定功能的一段小程序. 在面向对象编程的语言中,函数也叫方法. 2.函数的格式 修饰符 返回值类型 函数名(参数类型 实际参数,....) { 执行语句; retur ...
- java基础教程 类_Java零基础系列教程06初识类和对象
配套视频教程 万物皆对象 分类是人们认识世界的一个很自然的过程,在日常生活中会不自觉地进行分类 身边的对象 顾客 姓名-张浩 年龄-20 体重-60kg 操作: 购买商品 收银员 员工号-10001 ...
- java web 加载类_Java中用ClassLoader载入各种资源(类、文件、web资源)的方法
lassLoader主要对类的请求提供服务,当JVM需要某类时,它根据名称向ClassLoader要求这个类,然后由ClassLoader返回这个类的class对象. ClassLoader负责载入系 ...
最新文章
- 重磅!中国微纳机器人技术取得新突破,实现肿瘤的可视化精准治疗!
- [转]Extending the User Interface in Outlook 2010
- 「雅礼集训 2017 Day5」珠宝
- Unity3D 单例模式
- Spring Boot——LocalDateTime格式化配置
- springboot约定优于配置的体现
- html中文段落,HTML 段落-JavaScript中文网-JavaScript教程资源分享门户
- oracle不同库之间传送文件,EXCEL与ORACLE间的数据互传法数据库 -电脑资料
- LeetCode 1410. HTML 实体解析器(哈希map)
- params参数的调用
- 利用lightgbm做learning to rank 排序,解析模型中特征重要度
- Unicode字符串和非Unicode字符串
- win10重装后显示未安装任何音频输出设备
- 这几天阿里云发生故障事件,身为程序员慌得一批……
- Qt Style Sheet实践(二):组合框QComboBox的定制
- 使用 Sprinkles 构建您自己的类型安全版本的 Tailwind CSS
- QGIS基本功 | 12 图层的混合模式
- 我是如何把一套GitLab CI/CD课程做到全网第一的?
- 新氧用数据化作为分析 帮助用户甄选医美机构
- 现行的常用的文件格式类别 简析
热门文章
- 19年兰州大学计算机分数线,兰州大学2019年在广东省录取分数线
- 支持mysql的报表开发工具_你不知道的mysql的3W法,内附超好用的报表工具
- Java中string与String区别_JAVA中String与StringBuffer的区别
- SpringBoot2.6.1 elasticsearch7.1.5 Vue
- RuoYi-Cloud 部署篇_02(linux环境 mysql+nginx版本)
- String 常用API
- wsimport将wsdl生成java 调用时碰到的一个问题Could not initialize Service
- linux 动态传参执行shell脚本
- java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more
- 模型预测控制 索引超出数组元素的数目(0)。_C++基础总结(二):C++基本数据类型及流控制语句详解...