遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

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();
        }
    }
}

 

 

【bak】

 原文会持续更新,原文地址:https://www.cnblogs.com/uncleyong/p/15867779.html

 

posted @ 2022-02-07 18:06  全栈测试笔记  阅读(1108)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end