- package core;
- import java.sql.*;
- import java.util.Properties;
- import java.io.*;
- public class ConnDB {
- public Connection conn=null;
- public ResultSet rs=null;
- public Statement stmt=null;
- private static String propFileName="connDB.properties";
- private static Properties prop=new Properties();
- private static String dbClassName =
- "com.mysql.jdbc.Driver";
- private static String dbUrl =
- "jdbc:mysql://127.0.0.1:3306/db_library";
- private static String dbUser = "admin";
- private static String dbPwd = "111";
- private static void loadProperty() {
- try {
- prop.load(new FileInputStream(propFileName)); //通过文件输入流对象加载Properties文件
- dbClassName = prop.getProperty("DB_CLASS_NAME");
- dbUrl = prop.getProperty("DB_URL",
- "jdbc:mysql://127.0.0.1:3306/db_library");
- dbUser = prop.getProperty("DB_USER", "admin");
- dbPwd = prop.getProperty("DB_PWD", "111");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static Connection getConnection() {
- Connection conn = null;
- loadProperty();
- try {
- Class.forName(dbClassName).newInstance();
- conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);
- }
- catch (Exception ee) {
- ee.printStackTrace();
- }
- if (conn == null) {
- System.err.println(
- "警告: DbConnectionManager.getConnection() 获得数据库链接失败.rnrn链接类型:" +
- dbClassName + "rn链接位置:" + dbUrl + "rn用户/密码" + dbUser + "/" +
- dbPwd);
- }
- return conn;
- }
- /*
- *功能:执行查询语句
- */
- public ResultSet executeQuery(String sql) {
- try {
- conn = getConnection();
- stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- rs = stmt.executeQuery(sql);
- }
- catch (SQLException ex) {
- System.err.println(ex.getMessage());
- }
- return rs;
- }
- /*
- *功能:执行更新操作
- */
- public int executeUpdate(String sql) {
- int result = 0;
- try {
- conn = getConnection();
- stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- result = stmt.executeUpdate(sql);
- }
- catch (SQLException ex) {
- result = 0;
- }
- try {
- stmt.close();
- }
- catch (SQLException ex1) {
- }
- return result;
- }
- public int executeUpdate_id(String sql) {
- int result = 0;
- try {
- conn = getConnection();
- stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- result = stmt.executeUpdate(sql);
- String ID = "select @@IDENTITY as id";
- rs = stmt.executeQuery(ID);
- if (rs.next()) {
- int autoID = rs.getInt("id");
- result = autoID;
- }
- }
- catch (SQLException ex) {
- result = 0;
- }
- return result;
- }
- /*
- *功能:关闭数据库的连接
- */
- public void close() {
- try {
- if (rs != null) {
- rs.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace(System.err);
- }
- try {
- if (stmt != null) {
- stmt.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace(System.err);
- }
- try {
- if (conn != null) {
- conn.close();
- }
- }
- catch (Exception e) {
- e.printStackTrace(System.err);
- }
- }
- }