package com.mescs.baseinfo.utils; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory;/** * * 類(lèi)名:DatabaseUtil <br /> * * 功能:數(shù)據(jù)庫(kù)操作 * */ public class DatabaseUtil { private final static Logger LOGGER = LoggerFactory.getLogger(DatabaseUtil.class); private static final String DRIVER = "org.firebirdsql.jdbc.FBDriver"; private static final String URL = "jdbc:firebirdsql:embedded:mescs.fdb?lc_ctype=UTF8"; private static final String USERNAME = "root"; private static final String PASSWORD = "root"; private static final String SQL = "DELETE FROM ";// 數(shù)據(jù)庫(kù)數(shù)據(jù)庫(kù)表內(nèi)容清空 static { try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { LOGGER.error("數(shù)據(jù)庫(kù)驅(qū)動(dòng)加載失敗===>>>", e); } } /** * 獲取數(shù)據(jù)庫(kù)連接 * * @return */ public static Connection getConnection() { Connection conn = null; try { conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { LOGGER.error("數(shù)據(jù)庫(kù)連接失敗===>>>", e); } return conn; } /** * 關(guān)閉數(shù)據(jù)庫(kù)連接 * @param conn */ public static void closeConnection(Connection conn) { if(conn != null) { try { conn.close(); } catch (SQLException e) { LOGGER.error("數(shù)據(jù)庫(kù)關(guān)閉失敗===>>>", e); } } } /** * 獲取數(shù)據(jù)庫(kù)下的所有表名 */ public static List<String> getTableNames() { List<String> tableNames = new ArrayList<String>(); Connection conn = getConnection(); ResultSet rs = null; try { //獲取數(shù)據(jù)庫(kù)的元數(shù)據(jù) DatabaseMetaData db = conn.getMetaData(); //從元數(shù)據(jù)中獲取到所有的表名 rs = db.getTables(null, null, null, new String[] { "TABLE" }); while(rs.next()) { tableNames.add(rs.getString(3)); } } catch (SQLException e) { LOGGER.error("獲取數(shù)據(jù)庫(kù)表名失敗===>>>", e); } finally { try { rs.close(); closeConnection(conn); } catch (SQLException e) { LOGGER.error("關(guān)閉數(shù)據(jù)庫(kù)失敗===>>>", e); } } return tableNames; } /* * 清空數(shù)據(jù)庫(kù)表 */ public static void emptyDatabase() throws SQLException { List<String> tableNames = getTableNames(); Connection conn = getConnection(); PreparedStatement pStemt = null; for(String table:tableNames){ if(!table.equals("SYSPARAM") && !table.equals("T_CLEAR_DATA")){ String tableSql = SQL + table; try { pStemt = conn.prepareStatement(tableSql); Statement stmt=conn.createStatement(); stmt.executeUpdate(tableSql); } catch (SQLException e) { e.printStackTrace(); } } } conn.close(); } }
總結(jié):這里的數(shù)據(jù)庫(kù)用的Firebird數(shù)據(jù)庫(kù),當(dāng)然可以用Mysql,Oracle等主流數(shù)據(jù)庫(kù),方法也只是簡(jiǎn)單列出了刪除,增刪改查類(lèi)似,如法炮制。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com