为了项目容易管理,我们经常将变量统一放在resources 文件夹下,以.properties 文件进行存储。最常见的就是在进行数据库连接时配置的数据库连接数据。 1 解析配置文件.properties先在resources文件夹下新建jdbc.properties 文件 jdbc.driver = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/myDatabase jdbc.username = root jdbc.password = hwsofts08
代码 package com.autotesting;
import java.io.IOException; import java.util.Properties;
public class Test { public static void main(String[] args) { Properties properties = new Properties(); try { properties.load(Test.class.getClassLoader().getResourceAsStream("jdbc.properties")); } catch (IOException e) { e.printStackTrace(); } String url = properties.getProperty("jdbc.url"); String username = properties.getProperty("jdbc.username"); String password = properties.getProperty("jdbc.password"); System.out.println("url is: " + url); System.out.println("username is: " + username); System.out.println("password is: " + password); } }
执行结果: 为了连接MySQL数据库,需要先下载mysql-connector-java jar包。 下载地址: https:///artifact/mysql/mysql-connector-java/8.0.30
下载完成后,将mysql-connector-java-8.0.30.jar 文件复制到lib 文件夹下,然后右键选择Add as Library 语句 select * from student where sid = 18;
代码: package com.autotesting;
import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties;
public class ConnData { public static void main(String[] args) { String sql = "select * from student where sid = ?;"; Properties properties = new Properties(); try { properties.load(new FileInputStream(new File("src/main/resources/jdbc.properties"))); // 获取jdbc.properties文件中的数据 String url = properties.getProperty("jdbc.url"); String username = properties.getProperty("jdbc.username"); String password = properties.getProperty("jdbc.password"); // 获取Connection Connection connection = DriverManager.getConnection(url, username, password); // 获取PreparedStatement PreparedStatement preparedStatement = connection.prepareStatement(sql); // 设置条件字段值 preparedStatement.setObject(1, 18); // 调用查询方法获取结果集 ResultSet resultSet = preparedStatement.executeQuery(); // 从结果集获取查询数据 while(resultSet.next()){ String nameValue = resultSet.getObject("sname").toString(); String genderValue = resultSet.getObject("gender").toString(); String sidValue = resultSet.getObject("sid").toString(); System.out.println("sname is "+ nameValue + "; gender is " + genderValue + "; sid is " + sidValue); } } catch (Exception e) { e.printStackTrace(); } } }
执行结果 ------- 如果您觉得对您有帮助,请帮忙点一下公众号文中和最底部的广告,点一下就可以,谢谢~
|