Java数据库通用查询及封装

时常在网上看到,有关Java数据通用查询及封装的技术文章,前些日我在看书时突然想起以前怎么写jdbc查询的,好像当时没理顺,昨天晚上花了点时间,复习了一下写了两种通用数据封装。

文章只是为了复习而写,新手可以看看吧,大牛飘过。。。。

先把一些辅助类贴上来:

DBHelp.java获得连接及关闭资源
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBHelp {
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private String connStr = "jdbc:sqlserver://localhost:1433;DatabaseName=student";
private String userName = "sa";
private String userPass = "root";
private Connection connection = null;
public Connection getConnection() {
try {
connection = DriverManager.getConnection(connStr, userName,
userPass);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

public void closeResource(Object obj) {
try {
if (Connection.class.isInstance(obj)) {
((Connection) obj).close();
}
if (PreparedStatement.class.isInstance(obj)) {
((PreparedStatement) obj).close();
}

if (ResultSet.class.isInstance(obj)) {
((ResultSet) obj).close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public void closeResource(Connection connection,
PreparedStatement pStatement) {
try {
if (connection != null) {
connection.close();
}
if (pStatement != null) {
pStatement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

public void closeResource(Connection connection,
PreparedStatement pStatement,ResultSet resultSet) {
try {
if (connection != null) {
connection.close();
}
if (pStatement != null) {
pStatement.close();
}
if(resultSet != null){
resultSet.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpfsz.html