db.properties保存数据库信息,使用JdbcUtil.java作为连接数据库的工具类,是初学java+mysql的常见连接方式
package cn.xujingfeng;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JdbcUtil {
static String url = null;
static String user = null;
static String password = null;
static String driverClass = null;
static{
try {
Properties properties = new Properties();
InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
properties.load(in);
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driverClass = properties.getProperty("driverClass");
Class.forName(driverClass);
} catch (Exception e) {
e.printStackTrace();
System.out.println("驱动加载失败!");
throw new RuntimeException(e);
}
}
public static Connection getConnection(){
try {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void close(Connection conn,Statement st,ResultSet rs){
if(conn!=null){
try{
conn.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
if(st!=null){
try{
st.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
if(rs!=null){
try{
rs.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public static void close(Connection conn,Statement st){
if(conn!=null){
try{
conn.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
if(st!=null){
try{
st.close();
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
注意导包时eclipse具有mysql的两个包,一个是java.sql.*,一个是com.mysql.jdbc.*。前者是应该选择的,后者是针对mysql优化使用的。举例来说,Statement这个类在两个包里面都有,但是继承关系不太一致,总之就是属于两个不同的类,注意不要混淆使用两个包,如果出现什么莫名其妙的报错,注意看看是不是包导错了。
InputStream in = JdbcUtil.class.getResourceAsStream("/db.properties");
这样的目的是为了针对java project和java web project的路径不一致而设计的,前者编译过后的当前路径是bin,后者则会是tomcat的bin目录,有区别,使用getResourceAsStream能保证两者都能读取到db.properties文件
db.properties文件配置大致如下,根据个人数据库自行修改
url=jdbc:mysql://localhost:3306/test
user=root
password=root
driverClass=com.mysql.jdbc.Driver
这是最基础的连接数据库方式