properties文件编写
driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/student?useSSL=FALSE&serverTimezone=UTC
user=root
password=root
使用eclipse编写properties文件的时候注意将编码格式改为utf-8
,否则会因为字符转义问题报错
public class test {
private static String driver=null;
private static String url=null;
private static String user = null;
private static String password=null;
static{
try {
Properties properties = new Properties();
InputStream is = test.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(is);
//读取属性
driver = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName(driver);
Connection connection=DriverManager.getConnection(url,user,password);
Statement statement=connection.createStatement();
ResultSet rSet=statement.executeQuery("select*from students");
while(rSet.next()){
for (int i = 1; i < 7; i++) {
System.out.print(rSet.getString(i)+'\t');
}
System.out.println();
}
}
}
这里
是因为将properties文件放在了src目录下,需要使用类加载器,去读取src底下的资源文件。
如果放在根目录下,可以直接使用InputStream is = new FileInputStream("jdbc.properties")
去调用。