jdbc连接数据库

jdbc连接数据库:推荐使用第三种

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;

import org.junit.Test;

public class Demo1 {
    
    private String url = "jdbc:mysql://localhost:3306/test1";
    
    private String user = "root"; //用户名
    private String password ="123"; //密码
    
    @Test
    public void test1() throws Exception{
        Driver driver = new com.mysql.jdbc.Driver();
        
        
        Properties props = new Properties();
        props.setProperty("user", user);
        props.setProperty("password", password);
        
        Connection conn = driver.connect(url, props);
        
        System.out.println(conn);
    }
    
    /**
     * 使用驱动管理器类连接数据库(注册了2次)
     * @throws Exception
     */
    @Test
    public void test2() throws Exception {
        Driver driver = new com.mysql.jdbc.Driver();
        //注册
        DriverManager.registerDriver(driver);    //
        
        //连接具体的数据库
        Connection conn = DriverManager.getConnection(url,user,password);
        System.out.println(conn);
    }
    
    /**
     * 使用驱动管理器类连接数据库
     * @throws Exception
     */
    @Test
    public void test3() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        
        //连接具体的数据库
        Connection conn = DriverManager.getConnection(url,user,password);
        System.out.println(conn);
    }
}

 

posted @ 2016-09-12 14:57  微风星宇  阅读(104)  评论(0编辑  收藏  举报