java连接mysql数据库

来源:互联网 发布:淘宝直通车卡位软件 编辑:程序博客网 时间:2024/05/06 00:52

package com.db;

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

public class DBUtil {
 private static String url;
 private static String driver;
 private static String username;
 private static String password;

 // 第一次用到 DBUtil 时,加载配置文件
 static {
  try {
   // 获得资源文件流,资源文件路径:/db.properties
   InputStream in =
    DBUtil.class.getResourceAsStream(
      "db.properties");   
   // Properties 从流读数据,加载这些键值对
   Properties p = new Properties();
   p.load(in);
   in.close();   
   // 从 Properties 中取出配置属性,
   // 赋值给静态成员
   url = p.getProperty("url");
   driver = p.getProperty("driver");
   username = p.getProperty("username");
   password = p.getProperty("password");
   // 注册驱动
   Class.forName(driver);
   
//   // 显示加载的结果
//   System.out.println("DBUtil已经加载配置信息:");
//   System.out.println(url);
//   System.out.println(driver);
//   System.out.println(username);
//   System.out.println(password);
   
  } catch(Exception e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  }
 }
 
 public static Connection open()
       throws SQLException {
  return DriverManager.getConnection(
    url,username,password);
 }
 
 public static void close(ResultSet rs) {
  if(null == rs) return;
  try {rs.close();} catch(Exception e) {}
 }
 public static void close(Statement stmt) {
  if(null == stmt) return;
  try {stmt.close();} catch(Exception e) {}
 }
 public static void close(Connection con) {
  if(null == con) return;
  try {con.close();} catch(Exception e) {}
 }
 public static void close(
   ResultSet rs,Statement stmt) {
  close(rs);
  close(stmt);
 }
 public static void close(
   ResultSet rs,Statement stmt,Connection con) {
  close(rs, stmt);
  close(con);
 }
 public static void close(
   Statement stmt, Connection con) {
  close(stmt);
  close(con);
 }

 public static void main(String[] args) throws SQLException {
  Connection con = DBUtil.open();
  System.out.println(con);
  DBUtil.close(con);
 }

}

 

配置文件:

#configuration

url=jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=gbk
driver=com.mysql.jdbc.Driver
username=root
password=root