连接mysql

  总有一种情况,属于那种,代码明明很对,可是就是有意想不到的问题,找半天的bug,然后,关了eclipse 重新开,重新写

  就又对了,问题对的莫名其妙

  连接mysql:

package util;

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

public class DBHelper {
    private static final String driver = "com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/test";
    private static final String usernane = "root";
    private static final String password = "*****";
    private static Connection connection = null;
    static
    {
        try {
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public  static Connection getConnection() throws Exception
    {
        if (connection == null) {
            connection = DriverManager.getConnection(url,usernane,password);
            return connection;
        }
        return connection;
    }
    
    public static void main(String []args)
    {
        try
        {
            Connection connection = DBHelper.getConnection();
            if (connection!= null) {
                System.out.println("数据库连接正常");
            }
            else
            {
                System.out.println("数据库连接异常");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    
}

 

posted @ 2016-11-21 16:20  暖暖要坚持  阅读(155)  评论(0编辑  收藏  举报