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);
        }          
    }
  • 相关阅读:
    Windows10:家庭版如何设置开机自动登录
    Windows10:常用快捷键(转载)
    Windows10:找回传统桌面的系统图标
    MyBatis之XML映射文件详解
    MyBatis之核心对象及配置文件详解
    Java用Jsoup登录网站,以JSON格式提交(POST)数据,处理JSON格式返回结果,并将处理结果保存到系统剪贴板
    (转)总结.Net下后端的几种请求方式(WebClient、WebRequest、HttpClient)
    jvisualvm.exe 查看堆栈分配
    Hutool 常用的工具类和方法
    StringRedisTemplate 常用方法
  • 原文地址:https://www.cnblogs.com/StanLong/p/6885769.html
Copyright © 2011-2022 走看看