在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;
}
driver = com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3304/test?useUnicode=true&character=utf8&useSSL=true
username=root
password=123456
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();
}
}
}
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);
}
}
}
原文:https://www.cnblogs.com/cspx/p/14168098.html