原生jdbc工具包封装!!!

代码如下:没有配置文件db.properties,调用getConnection()会自动生成,然后自己填写配置文件

package cn.viwiv.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBUtils {
	private static String driver;
	private static String url;
	private static String username;
	private static String password;
	static {
		Properties properties = new Properties();
		FileInputStream inputStream = null;
		try {
			inputStream = new FileInputStream("db.properties");
			try {
				properties.load(inputStream);
			} catch (IOException e) {
				throw new RuntimeException("配置文件 问题!!!");
			}
		} catch (FileNotFoundException e) {
			File file = new File("db.properties");
			if(!file.exists()) {
				try {
					file.createNewFile();
					BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
					bufferedWriter.write("driver = driver");
					bufferedWriter.newLine();
					bufferedWriter.write("url = url");
					bufferedWriter.newLine();
					bufferedWriter.write("username = username");
					bufferedWriter.newLine();
					bufferedWriter.write("password = password");
					bufferedWriter.newLine();
					bufferedWriter.flush();
					bufferedWriter.close();
				} catch (IOException e1) {
					throw new RuntimeException("db.properties文件不存在!!!我们为你创建时失败!!!");
				}
			}
			throw new RuntimeException("db.properties文件不存在!!!我们已经为你创建了!!快去填写信息!!");
		}
		driver = properties.getProperty("driver", null);
		url = properties.getProperty("url", null);
		username = properties.getProperty("username", null);
		password = properties.getProperty("password", null);
		if(driver == null || url == null || username == null || password == null) {
			throw new RuntimeException("配置问题!!!!");
		}else {
			try {
				Class.forName(driver);
			} catch (ClassNotFoundException e) {
				throw new RuntimeException("请检查驱动!!!");
			}
		}
	}
	
	public static Connection getConnection() {
		Connection connection = null;
		try {
			connection = DriverManager.getConnection(url,username,password);
		} catch (SQLException e) {
			throw new RuntimeException("连接数据库失败,检查账户、密码!!!");
		}
		return connection;
	}
	
	public static void close(Connection connection, Statement statement, ResultSet resultSet) {
		try {
			if(resultSet != null) {
				resultSet.close();
			}
			if(statement != null) {
					statement.close();
			}
			if(connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			throw new RuntimeException("关闭异常!!!");
		}
	}
	
}

你可能感兴趣的:(Java,数据库)