建立文件:dp.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/new_schema password=your-password username=root
放在jdbc工具类中
Properties properties=new Properties();//创建文件对象
properties.load(new FileInputStream(“D:\javac\projects\jdbc学习\src\dp.properties”));// 读取文件
再赋值
driverClassName=properties.getProperty(“driverClassName”);
url=properties.getProperty("url"); password=properties.getProperty("password"); usernane=properties.getProperty("username");
import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class TYBU { private static final String driverClassName; private static final String url; private static final String password; private static final String usernane; static { Properties properties=new Properties(); try { properties.load(new FileInputStream("D:\\javac\\projects\\jdbc学习\\src\\dp.properties")); } catch (IOException e) { e.printStackTrace(); } driverClassName=properties.getProperty("driverClassName"); url=properties.getProperty("url"); password=properties.getProperty("password"); usernane=properties.getProperty("username"); //url="jdbc:mysql://localhost:3306/new_schema"; //driverClassName="com.mysql.jdbc.Driver"; //password="your-password"; //usernane="root"; } public static void loadDriver() throws ClassNotFoundException { try{ Class.forName(driverClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection(){ Connection conn=null; try { loadDriver(); conn= DriverManager.getConnection(url,usernane,password); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; }}
结果:
配置成功
在测试运行了