首页 > 数据库技术 > 详细

java连接MySQL 工具类

时间:2020-10-27 23:14:54      阅读:45      评论:0      收藏:0      [点我收藏+]
第一部分:工具类作用:
    解决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();
}
}
}
}

java连接MySQL 工具类

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!