java mysql 连接工具类,java连接MySQL 工具类

第一部分:工具类作用:

解决JDBC 代码重复度太高 --- 将几个固定的功能 抽取封装到 几个函数中

1、为了简便用户操作

2、具有通用性

第二部分:JDBC事务操作

数据库事务(Transaction)是由若干个SQL语句构成的一个操作序列。数据库系统保证在一个事务中的所有SQL要么全部执行成功,要么全部不执行。

Connection conn = openConnection();

try {

// 关闭自动提交,开启手动事务:

conn.setAutoCommit(false);

// 执行多条SQL语句:

insert(); update(); delete();

// 提交事务:

conn.commit();

} catch (SQLException e) {

// 回滚事务:

conn.rollback();

} finally {

conn.setAutoCommit(true);

conn.close();

}

(开启手动事务的关键是con.setAutoCommit(false),JDBC事务默认是开启的,并且是自动提交)

package utils;

import java.io.FileReader;

import java.io.IOException;

import java.net.URL;

import java.sql.*;

import java.util.Properties;

public class jdbcutils {

private static String url1 = null;

private static String password = null;

private static String user = null;

public static void main(String[] args) {

jdbcutils jdbcutils = new jdbcutils();

jdbcutils.getConnection();

}

static {

Properties pro = new Properties();

try {

ClassLoader classLoader = jdbcutils.class.getClassLoader();

URL resour = classLoader.getResource("jdbc.properties");

String path = resour.getPath();

pro.load(new FileReader(path));

} catch (IOException e) {

e.printStackTrace();

}

url1 = pro.getProperty("url");

password = pro.getProperty("password");

user = pro.getProperty("user");

String driver = pro.getProperty("driver");

try {

Class.forName(driver);

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

public static Connection getConnection() {

try {

return DriverManager.getConnection(url1, user, password);

} catch (SQLException throwables) {

throwables.printStackTrace();

return null;

}

}

public static void close(Connection conn, Statement stat){

if (stat != null){

try {

stat.close();

} catch (SQLException throwables) {

throwables.printStackTrace();

}

}

if (conn != null){

try {

conn.close();

} catch (SQLException throwables) {

throwables.printStackTrace();

}

}

}

public static void close(Connection conn, Statement stat,ResultSet rs){

if (rs != null){

try {

rs.close();

} catch (SQLException throwables) {

throwables.printStackTrace();

}

}

if (stat != null){

try {

stat.close();

} catch (SQLException throwables) {

throwables.printStackTrace();

}

}

if (conn != null){

try {

conn.close();

} catch (SQLException throwables) {

throwables.printStackTrace();

}

}

}

}

原文:https://www.cnblogs.com/aw123/p/13887548.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值