jdbc获取数据库连接的四种方式

方式一:

@Test
public void test01() throws SQLException {
    // 创建一个数据库驱动器对象
    Driver driver = new Driver();
    // url地址
    String url = "jdbc:mysql://localhost:3306/girls";
    // 创建一个Properties对象,将账号和密码放进去
    Properties pro = new Properties();
    pro.setProperty("user", "root");
    pro.setProperty("password", "root");
    // 传参进行连接
    Connection connect = driver.connect(url, pro);
    System.out.println(connect);
}

方式二:

@Test
public void test02() throws Exception {
    // 通过反射来实例化Driver对象
    Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver) aClass.newInstance();
    // url地址
    String url = "jdbc:mysql://localhost:3306/girls";
    // 创建一个Properties对象,将账号和密码放进去
    Properties pro = new Properties();
    pro.setProperty("user", "root");
    pro.setProperty("password", "root");
    // 传参进行连接
    Connection connect = driver.connect(url, pro);
    System.out.println(connect);
}

方式三:

@Test
public void test3() throws SQLException, ClassNotFoundException {
    // 加载驱动
    Class.forName("com.mysql.jdbc.Driver");
    // 获取链接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "root");
    System.out.println(connection);
}

方式四:

1.写一个配置文件,db.properties

url = jdbc:mysql://localhost:3306/girls
username = root
password = root
classDriver = com.mysql.jdbc.Driver
@Test
public void test4() throws Exception {
    // 读取配置文件
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/lili/db.properties");
    // 加载配置文件
    Properties properties = new Properties();
    properties.load(in);
    // 获取属性值
    String url = properties.getProperty("url");
    String username = properties.getProperty("username");
    String classDriver = properties.getProperty("classDriver");
    String password = properties.getProperty("password");
    // 加载驱动
    Class.forName(classDriver);
    // 连接
    Connection connection = DriverManager.getConnection(url, username, password);
    System.out.println(connection);
}
posted @   JamieChyi  阅读(19)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示