创建类
package com.foot.lesson03;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Properties;
public final class JdbcUtil {
public static void main(String[] args) {
String url = null;
String user = null;
String password = null;
//获取配置文件
Properties p = new Properties();
File file = new File(System.getProperty("user.dir") + "//src//jdbc.properties");
try {
p.load(new FileInputStream(file));
//获取方法一:不知道配置文件内的key值
Iterator<Object> iterator = p.keySet().iterator();
while(iterator.hasNext()) {
String key = (String)iterator.next();
String value = p.getProperty(key);
System.out.println(key + "----" + value);
}
//获取方法二:知道key值,只需要获取需要的内容
url = p.getProperty("url");
user = p.getProperty("user");
password = p.getProperty("password");
System.out.println(user + "--" + password + "--" + url);
} catch (Exception e) {
e.printStackTrace();
}
//数据库的连接
Connection connection = JdbcUtil.getConnection(url, user, password);
try {
connection.prepareStatement("");//写入Sql语句
} catch (SQLException e) {
e.printStackTrace();
}
}
}
数据库连接代码
/**
* get the connection of mysql
* @return
*/
public static Connection getConnection(String url, String user, String password) {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* close the resource
* @param rs
* @param statement
* @param connection
*/
public static void release(ResultSet rs, Statement statement, Connection connection) {
if(null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != statement) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != connection) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
资源文件 ##
在本工程的src目录下创建文件jdbc.properties文件,在文件内加入内容如下:
url=jdbc:mysql://117.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
user=root
password=……你的密码
注意事项
JDK较低的版本,需要加入驱动,本历程没有加入驱动包。