java 数据库 properties_Java通过Properties加载数据库

通过配置文件加载数据库

前言

在b站上看了狂神的MySql,没写过的博客的我第一次有了写一篇博客的想法,但最近又是期末,时间比较紧张。就自己动手码了一遍,其中也有很多不清楚的知识,在这里总结一下。

Properties类: 继承自HashTable(HashTable又是什么-。-),直接已知子类有Provider。用于在java中配置文件。.properties文件中以键值对的方式存放数据。

用到的方法:getProperty(String)获取属性

//在此属性列表中搜索具有指定键的属性。如果在此属性列表中找不到该键,则会检查默认属性列表及其默认值(递归)。如果未找到该属性,则该方法返回默认值参数。

public String getProperty(String key) {

Object oval = this.map.get(key);

String sval = oval instanceof String ? (String)oval : null;

Properties defaults;

return sval == null && (defaults = this.defaults) != null ? defaults.getProperty(key) : sval;

}

public String getProperty(String key, String defaultValue) {

String val = this.getProperty(key);

return val == null ? defaultValue : val;

}

代码

1.创建properties文件

driver = com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3304/test?useUnicode=true&character=utf8&useSSL=true

username=root

password=123456

2.通过反射获得相同src目录下的properties文件

public class utils {

private static String driver = null;

private static String url = null;

private static String username = null;

private static String password = null;

static {

try {

InputStream in = utils.class.getClassLoader().getResourceAsStream("db.properties");

Properties properties = new Properties();

properties.load(in);

driver = properties.getProperty("driver");

url = properties.getProperty("url");

username = properties.getProperty("username");

password = properties.getProperty("password");

//加载驱动

Class.forName(driver);

} catch (Exception e) {

e.printStackTrace();

}

}

//获取连接

public static Connection getConnection() throws SQLException {

return DriverManager.getConnection(url);

}

//释放连接

public void release(ResultSet resultset, Connection connection, PreparedStatement preparedStatement) throws SQLException {

if (resultset != null){

resultset.close();

}

if (connection != null){

connection.close();

}

if (preparedStatement != null){

preparedStatement.close();

}

}

}

3.测试SQL插入

package com.ctgu.px.ctgu.px;

import com.ctgu.px.JdbcTest;

import java.sql.*;

/**

* @author px

*/

public class TestInsert {

public static void main(String[] args) throws SQLException {

Connection connection = null;

PreparedStatement statement = null;

ResultSet resultSet = null;

try {

//获得数据库连接

connection = utils.getConnection();

//获得SQL的执行对象

statement = (PreparedStatement) connection.createStatement();

//

String sql = "";

int i = statement.executeUpdate(sql);

if (i != 0) {

System.out.println("插入成功!");

}

} catch (SQLException e) {

e.printStackTrace();

}finally {

utils.release(connection, statement, null);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值