zoukankan      html  css  js  c++  java
  • JDBC连接MySQL数据库

    首先导入mysql的驱动jar包

    1、第一种方法

    
    

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

    import org.junit.Test;

    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、第二种方法

    
    
    
    

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

    
    

    import org.junit.Test;

    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、第三种方法

     

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

    
    

    import org.junit.Test;

    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);
        }          
    }
  • 相关阅读:
    归并排序
    msp430的时钟源设计
    插入排序
    msp430F5438A 的中断初步
    算法导论,第一节第二节课总结
    MSP430F5438A的时钟系统
    msp430F5438A 的ADC 研究
    图像处理基本原理(转载)
    C++标准库简介
    C# 接口 抽象类
  • 原文地址:https://www.cnblogs.com/StanLong/p/6885769.html
Copyright © 2011-2022 走看看