最近一直在学习hibernate,一回想起JDBC感觉陌生了好多,刚才编了个小程序复习一下,我这里把JDBC的连接写在一个类里,这样我们就可以只写一遍这些连接了,简化了代码也方便了调用。
package jdbctest;
import java.sql.*;
public class JDBCinit {
public static Connection getConnection(){
Connection conn = null ;
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接,账号密码根据自己数据库进行填写
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=xxx&password=xxx");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return conn;
}
//创建状态对象,以便发送SQL语句到数据库
public static Statement getStatement(Connection conn){
Statement stmt = null;
try {
stmt = conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
//从数据库里进行查询操作
public static ResultSet getResultSet(Statement stmt,String sql){
ResultSet rs = null;
try {
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//关闭结果集
public static void getClose(ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//关闭statement对象
public static void getClose(Statement stmt){
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//关闭数据库连接
public static void getClose(Connection conn){
if(conn != null){
try {
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
接着我们再写一个测试类,来验证下我们写的到底对不对
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) {
Connection conn =JDBCinit.getConnection();
Statement stmt = JDBCinit.getStatement(conn);
//根据自己的数据库进行查询
ResultSet rs = JDBCinit.getResultSet(stmt, "select * from xxx");
try {
while(rs.next() == true){
//xxx为数据库字段名,更具实际情况填写
System.out.println("password:"+rs.getString("xxx"));
}
} catch (SQLException e) {
e.printStackTrace();
}
JDBCinit.getClose(rs);
JDBCinit.getClose(stmt);
JDBCinit.getClose(conn);
}
}
大功告成~~~