小朋友你是否有很多问号????????????
1、在资源文件中建一个文件,填入连接数据库的基本信息。
2、通过反射拿到资源文件。
你说你不只知道什么是反射????? (那你可得认真看这篇博客了)
你还不会反射吧,快来吧!!!_明天更新的博客-CSDN博客
Class<Doem> doemClass = Doem.class;InputStream is = doemClass.getClassLoader().getResourceAsStream("DomeJdbc");
2. 取出资源文件中的连接信息。。。
Class<Doem> doemClass = Doem.class;InputStream is = doemClass.getClassLoader().getResourceAsStream("DomeJdbc");//InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("DomeJdbc");Properties prop = new Properties();try {prop.load(is);String driver = prop.getProperty("db.driver");String url = prop.getProperty("db.url");String username = prop.getProperty("db.username");String password = prop.getProperty("db.password");} catch (Exception e) {}}}
3.连接数据库,编写代码。
/** Copyright (c) 2020, 2023, All rights reserved.**/
package cn.scl;import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;import java.io.InputStream;
import java.sql.*;
import java.util.Properties;/*** <p>Project: jdbcfirst - Doem</p>* <p>Powered by scl On 2023-08-11 13:55:30</p>* <p>描述:<p>** @author scl [1846080280@qq.com]* @version 1.0* @since 17*/
public class Doem {@Testvoid show1() {Class<Doem> doemClass = Doem.class;InputStream is = doemClass.getClassLoader().getResourceAsStream("DomeJdbc");//InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("DomeJdbc");Properties prop = new Properties();try {prop.load(is);String driver = prop.getProperty("db.driver");String url = prop.getProperty("db.url");String username = prop.getProperty("db.username");String password = prop.getProperty("db.password");//Class.forName(driver);Connection con = DriverManager.getConnection(url, username, password);System.out.println(con);Statement st = con.createStatement();for (int i = 0; i < 10; i++) {st.execute(String.format("create database if not exists user%d",i));}} catch (Exception e) {}}}
看结果: