码迷,mamicode.com
首页 > 数据库 > 详细

JDBC连接MySQL数据库

时间:2017-05-21 20:34:38      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:sys   demo1   nec   catch   ring   new   out   lex   word   

首先导入mysql的驱动jar包

1、第一种方法

public class Demo1 {
    //jdbc协议:数据库子协议://主机:端口号/连接的数据库
    private String url = "jdbc:mysql://localhost:3306/test";
    private String user = "root";
    private String password = "root";
      
    @Test  
    public void test1(){
        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、第二种方法

public class Demo2 {
    //jdbc协议:数据库子协议://主机:端口号/连接的数据库
    private String url = "jdbc:mysql://localhost:3306/test";
    private String user = "root";
    private String password = "root";
      
    @Test  
    public void test2(){
        Driver driver = new com.mysql.jdbc.Driver();
        //1、注册驱动程序(可以注册多个程序)
        DriverManager.registerDriver(driver);
        
        //2、连接到具体数据库
        Connection conn = DriverManager.getConnection(url,user,password);
        System.out.println(conn);
    }          
}
//分析Driver类的源码这样写道
static {
  try{
   java.sql.DriverManager.registerDriver(new Driver());
  }catch(SQLException e){
   throw new RuntimeException("Can‘t register driver!");
  }
 }  
//静态代码块在加载类的时候就已经执行了,所以上面的代码相当于注册了两次。改进方法二,得方法3
    

3、第三种方法

public class Demo3{
    //jdbc协议:数据库子协议://主机:端口号/连接的数据库
    private String url = "jdbc:mysql://localhost:3306/test";
    private String user = "root";
    private String password = "root";
      
    @Test  
    public void test3() throws Exception{
        Class.forName("com.mysql.jdbc.Driver");
        
        Connection conn = DriverManager.getConnection(url,user,password);
        System.out.println(conn);
    }          
}

 

JDBC连接MySQL数据库

标签:sys   demo1   nec   catch   ring   new   out   lex   word   

原文地址:http://www.cnblogs.com/StanLong/p/6885769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!