当前位置:Gxlcms > 数据库问题 > JDBC连接MySQL数据库

JDBC连接MySQL数据库

时间:2021-07-01 10:21:17 帮助过:24人阅读

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   

人气教程排行