JDBC连接MySql数据库


static代码块在main方法之前执行

package test;

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


public class TestConnection {

    public static void main(String[] args) {
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 根据给定的参数获取数据库连接
            Connection connection = DriverManager
                    .getConnection(
                            "jdbc:mysql://localhost:3306/db_wh?useUnicode=true&characterEncoding=utf8",
                            "root", "11111");
            System.out.println(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}


Mysql.properties
    #数据库连接URL
    url=jdbc:mysql://localhost:3306/db_wh?useUnicode=true&characterEncoding=utf8
    #数据库连接驱动
    driver=com.mysql.jdbc.Driver
    #数据库连接用户名
    username=root
    #数据库连接密码
    password=11111
    
    
    package com.web03.util;

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

public class MysqlDBUtil {
    
    //定义静态变量(四个参数 驱动类、地址、用户密码)
    private static String driver=null;
    private static String url=null;
    private static String username=null;
    private static String password=null;
    
    //使用静态代码的特性进行配置文件的读取并赋值给上面的静态变量
    static{
        Properties properties = new Properties();
        try {
            properties.load(MysqlDBUtil.class.getClassLoader().getResourceAsStream("Mysql.properties"));    
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //加载驱动类
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 获取mysql连接
     * */
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    /**
     * 关闭mysql连接
     * */
    public static void close(Connection connection){
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        System.out.println(MysqlDBUtil.getConnection());
    }
}

posted @ 2015-08-31 15:50  Tsoi  阅读(57)  评论(0)    收藏  举报