jdbc是连接数据库必不可少的工具,但每次连接都要重新写一遍太麻烦了,也不利于代码的可读性,这里做一个工具类进行封装。
package com.gh; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle; /**
* 注意首先导驱动包。。。。。。。。。。。
*
* @author ganhang
*
*/
public class JdbcUtil {
// 驱动类
public static String Driver;
// 数据库地址
public static String url;
// 数据库用户名
public static String user;
// 数据库密码
public static String password;
// 用配置文件 改动只需重启
public static ResourceBundle rb = ResourceBundle.getBundle("com.gh.jdbc_config");
static {
Driver = rb.getString("jdbc.Driver");
url = rb.getString("jdbc.url");
user = rb.getString("jdbc.user");
password = rb.getString("jdbc.password");
try {
Class.forName(Driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} // 防止实例化
private JdbcUtil() {} public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
System.out.println("连接失败!");
}
return conn;
} public static void close(ResultSet rs, Statement s, Connection c) {
try {
if (rs != null)
rs.close();
if (s != null)
s.close();
if (c != null)
c.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.gh; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 测试
* @author ganhang
*
*/
public class test {
public static void main(String[] args) {
Connection conn=JdbcUtil.getConnection();
String sql="select * from test";
try {
PreparedStatement ps=conn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1));
}
JdbcUtil.close(rs, ps, conn);
} catch (SQLException e) {
e.printStackTrace();
} }
}
jdbc.Driver=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.user=scott
jdbc.password=.
配置文件