练习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;

/**
* @公众号 : 全栈测试笔记、
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);
}
}



JDBC(解析properties)_sql


练习2:从数据库查询数据

JDBC(解析properties)_javascript_02

JDBC(解析properties)_java_03



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;

/**
* @公众号 : 全栈测试笔记
*/
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();
}
}
}



JDBC(解析properties)_sql_04

声明:如有侵权,请联系删除。