zoukankan      html  css  js  c++  java
  • JDBC 连接数据库工具类(properties文件)

    JDBC 连接数据库工具类

    Java 类

    package com.zhanggaosong.util;

    import java.io.InputStream;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.Properties;

    public class MyDBUtil {
    private static String driver = null;
    private static String url = null;
    private static String userName = null;
    private static String password = null;
    private static ThreadLocal<Connection> tong = new ThreadLocal<Connection>();

    static {
    try {
    Properties p = new Properties();

    InputStream inStream = MyDBUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");

    p.load(inStream);
    driver = p.getProperty("driver");
    url = p.getProperty("url");
    userName = p.getProperty("userName");
    password = p.getProperty("password");

    } catch (Exception e) {
    e.printStackTrace();
    }
    }

    public static Connection getConnetion() {
    Connection conn = null;
    try {
    conn=tong.get();
    if(conn==null){
    conn=DriverManager.getConnection(url,userName,password);
    tong.set(conn);
    }
    } catch (SQLException e) {
    e.printStackTrace();
    }
    return conn;
    }


    public static void closeConnection(){
    Connection conn = tong.get();
    if(conn!=null){
    try {
    conn.close();
    tong.set(null);
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    }

    jdbc.properties文件

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://127.0.0.1:3306/数据库名
    userName=root
    password=123456

  • 相关阅读:
    python---装饰器用法小结
    python---mysql事务
    python---sql语句集体更改数据
    python多继承中的深度优先与广度优先
    python---copy
    vue 主次页面区分
    css 过渡动画
    android web外壳
    cordova 打包 守护进程无法启动
    JavaScript 原生控制元素添加删除
  • 原文地址:https://www.cnblogs.com/zhanggaosong/p/3163228.html
Copyright © 2011-2022 走看看