采用JDBCUtils连接mysql

1.database.properties
src目录下创建文件,命名为:database.properties
键入以下信息:
包含各种数据库:#号为注释掉的。(数据库名称,用户名,密码按照自己的修改)

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/loginreg?characterEncoding=utf-8
username=root
pwd=root
## mysql database driver
#MySQLdriverClass=com.mysql.jdbc.Driver
#MySQLurl=jdbc:mysql://127.0.0.1/test?useSSL=false
#MySQLusername=root
#MySQLpassword=wsw011152
## sqlserver 2008 database driver
#SqlServerdriverClass=net.sourceforge.jtds.jdbc.Driver
#SqlServerurl=jdbc:jtds:sqlserver://localhost:1433;DatabaseName=test;
#SqlServerusername=sa
#SqlServerpassword=sa
## Oracle  database driver
#OracledriverClass=oracle.jdbc.driver.OracleDriver
#Oracleurl=jdbc:oracle:thin:@localhost:1521:test
#Oracleusername=scott
#Oraclerpassword=tiger

2.新建类:PropertiesUtil

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesUtil {
   private static Properties prop;
   static{
        try {
            prop = new Properties();
            String path = Thread.currentThread().getContextClassLoader().getResource("database.properties").getPath();
            System.out.println(path);
            prop.load(new FileInputStream(path));
        } catch (FileNotFoundException e) {
            System.out.println("加载配置文件失败");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 获取key的信息
    public static String getString(String key){
        return prop.getProperty(key);
    }
}

3.新建
JDBCUtils类

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtils {
	private static String url = PropertiesUtil.getString("url");
	private static String user = PropertiesUtil.getString("username");
	private static String password = PropertiesUtil.getString("pwd");
	//加载驱动
	static {
		try {
			Class.forName(PropertiesUtil.getString("driverClass"));
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	private static Connection conn;
	public static Connection getConnection() {
		System.out.println(url);
		try {
			if (conn ==null||conn.isClosed()) {
				conn = DriverManager.getConnection(url, user, password);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	//关闭资源
		public static void close(Connection conn,Statement stmt,ResultSet rs) throws SQLException{
			if (conn != null && !conn.isClosed()) {
				conn.close();
			}
			if (stmt != null && !stmt.isClosed()) {
				stmt.close();
			}
			if (rs != null && !rs.isClosed()) {
				rs.close();
			} 
		}
}

可以愉快的使用了。

你可能感兴趣的:(javaee)