JDBC(含解析properties)
练习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
__EOF__
本文作者:持之以恒(韧)
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!
关于博主:擅长性能、全链路、自动化、企业级自动化持续集成(DevTestOps)、测开等
面试必备:项目实战(性能、自动化)、简历笔试,https://www.cnblogs.com/uncleyong/p/15777706.html
测试提升:从测试小白到高级测试修炼之路,https://www.cnblogs.com/uncleyong/p/10530261.html
欢迎分享:如果您觉得文章对您有帮助,欢迎转载、分享,也可以点击文章右下角【推荐】一下!