java_JDBC连接数据库工厂
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//方法工厂模式
//JDBC数据库连接工厂类
public class ConnectionFactory {
private Connection conndb=null;
private PreparedStatement pstmt=null;
private ResultSet rs=null;
private final String DRIVER="com.microsoft.sqlserver.jdbc.SQLServerDriver";
private final String URL="jdbc:sqlserver://localhost:1433;databaseName=UserInfo";
private final String NAME="sa";
private final String PASSWORD="sa";
//构造方法 加载驱动
public ConnectionFactory(){
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//得到数据库连接
private void getConnectionDB(){
try {
conndb=DriverManager.getConnection(URL,NAME,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭数据库连接
public void closeConnection(){
try {
if(rs!=null){rs.close(); }
if(pstmt!=null){pstmt.close(); }
if(conndb!=null){conndb.close(); }
} catch (SQLException e) {
e.printStackTrace();
}
}
//查询数据表,并返回结果集
public ResultSet selectSQL(String sql){
try {
getConnectionDB();
pstmt=conndb.prepareStatement(sql);
System.out.println(sql);
rs=pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//添加,修改,删除数据信息
public int updateSQL(String sql){
int count=0;
try {
getConnectionDB();
pstmt=conndb.prepareStatement(sql);
System.out.println(sql);
count=pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
}