練習1:解析配置文件jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.168.168:3360/gifts?useUnicode=true&characterEncoding=utf-8&useSSL=true jdbc.username=root jdbc.password=123456
代碼:
package com.qzcsbj; import java.io.IOException; import java.util.Properties; /** * @公眾號 : 全棧測試筆記 * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <> */ 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 = " + url); System.out.println("username = " + username); System.out.println("password = " + password); } }
練習2:從數據庫查詢數據
package com.qzcsbj; 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; /** * @公眾號 : 全棧測試筆記 * @博客 : www.cnblogs.com/uncleyong * @微信 : ren168632201 * @描述 : <> */ public class Test { public static void main(String[] args) { String sql = "select username,job from users where id = ?"; Properties properties = new Properties(); try { // 解析配置 properties.load(new FileInputStream(new File("src\\main\\resources\\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,1); // 調用查詢方法獲取結果集 ResultSet resultSet = preparedStatement.executeQuery(); // 從結果集獲取查詢數據 while (resultSet.next()){ String usernameValue = resultSet.getObject("username").toString(); String jobValue = resultSet.getObject("job").toString(); System.out.println("username:"+ usernameValue +", job:" + jobValue); } } catch (Exception e) { e.printStackTrace(); } } }
原文會持續更新,原文地址:https://www.cnblogs.com/uncleyong/p/15867779.html