数据库连接类
[code="java"]package cn.qm.db;
import java.sql.*;
public class DataBase {
private Connection con;
private PreparedStatement pstmt;
private Statement stmt;
private ResultSet rs;
private String url;
private String user;
private String password;
public DataBase(){
url = "jdbc:mysql://localhost:3306/JXC?useUnicode=true&characterEncoding=UTF-8";//数据库连接路径
user = "root";
password = "root";
}
public Connection connection(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,user,password);
} catch (Exception e) {
System.out.println("数据库链接出错!请检查是否导入了MySQL的jar包?");
e.printStackTrace();
}
return con;
}
public PreparedStatement preparedstatement(String si){
try {
pstmt = connection().prepareStatement(si);
} catch (SQLException e) {
e.printStackTrace();
}
return pstmt;
}
public Statement statement(){
try {
stmt = connection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
return stmt;
}
public ResultSet resultset(String si){
try {
rs = statement().executeQuery(si);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
如果是MySQL数据库,则:
url = "jdbc:mysql://localhost:3306/JXC?useUnicode=true&characterEncoding=UTF-8";//数据库连接路径
user = "root";
password = "root";
Class.forName("com.mysql.jdbc.Driver");
如果是Oracle数据库,则:
url = "jdbc:oracle:thin:@localhost:1521:orcl";//数据库连接路径
user = "jwdc";
password = "sundun";
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();