当前位置:网站首页>JDBC 的四种连接方式 直接上代码

JDBC 的四种连接方式 直接上代码

2022-07-06 09:24:00 MSjan

废话少说 上代码 原创手写

package JDBCbutton.FristStudy;

import com.mysql.jdbc.Driver;
import org.junit.Test;

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

public class Day02 {
    public void connect1() throws SQLException {
        //1.注册驱动
        Driver driver = new Driver();
        //2.得到链接
        //jdbc:mysql:// 是协议
        //localhost 主机,可以是IP地址
        //3306 表示mysql监听的端口
        //hsp_db02 连接的数据库
        String url = "jdbc:mysql://localhost:3306/zzs_db01";
        // 把 账号密码 放入Properties 对象中
        Properties properties =new Properties();
        //user 和 password 是规定好的 后面实际情况写
        properties.setProperty("user","root");
        properties.setProperty("password","123123");

        //获取连接
        Connection connect  =driver.connect(url,properties);
    }
    @Test
    public void connect2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
       Class<?> aClass =Class.forName("com.mysql.jdbc.Driver");
       //
        Driver driver =(Driver) aClass.newInstance();

        String url = "jdbc:mysql://localhost:3306/zzs_db01";

        Properties properties =new Properties();
        properties.setProperty("user","root");
        properties.setProperty("password","123123");

        Connection connect  =driver.connect( url ,properties);

        System.out.println("方式二= " +connect);
    }
    @Test
  

    public void connect3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        Class<?> aClass =Class.forName("com.mysql.jdbc.Driver");

        Driver driver =(Driver) aClass.newInstance();
        String url ="jdbc:mysql://localhost:3306/zzs_db01";
        String user="root";
        String password="123123";

        DriverManager.registerDriver(driver);

        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println("方法三 = "+connection);


    }
    @Test
    public void connect4() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");//使用反射加载


        String url ="jdbc:mysql://localhost:3306/zzs_db01";
        String user="root";
        String password="123123";

        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println("第四种方法="+connection);
    }

}

收藏起来 忘了可以看看 !!

别忘了点赞哦

原网站

版权声明
本文为[MSjan]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_62927851/article/details/124828507