在QMaster分类里记录的相关源码是个人认为写得比较好、比较有用(可复用程度比较高)的一部分,并非QMaster的全部源码。欢迎评论。

dbconfig.xml

<?xml version="1.0" encoding="GB2312"?>
<!--数据库配置文件-->
<dbconfig>
    <jdbcdriver>com.mysql.jdbc.Driver</jdbcdriver><!--JDBC Driver-->
    <jdbcurl>jdbc:mysql://localhost:3306/questionnaire</jdbcurl><!--JDBC URL-->
    <dbuser>root</dbuser><!--数据库用户名-->
    <dbpwd>yarpee19890607</dbpwd><!--数据库密码-->
</dbconfig>

DBConfig.java

/**
 * 功能:解析dbconfig.xml文件,提供数据库配置。
 */
package db;

import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class DBConfig {
    //对应dbconfig.xml中的配置
    private String jdbcDriver;
    private String jdbcUrl;
    private String dbUser;
    private String dbPwd;

    DBConfig() throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory docBuildFac = DocumentBuilderFactory.newInstance();//生成一个DOM解析器工厂
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("dbconfig.xml");//相对位置src/dbconfig.xml
        Document doc = docBuildFac.newDocumentBuilder().parse(is);//生成一个DOM解析器,并解析dbconfig.xml生成Doc。
        Element root = doc.getDocumentElement();//根结点
        NodeList nodeList = root.getChildNodes();//根结点的子结点链表
        for(int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);//子结点
            if(node.getNodeType() == Node.ELEMENT_NODE) {
                if(node.getNodeName().equals("jdbcdriver")) {
                    jdbcDriver = node.getFirstChild().getNodeValue();//DOM把<node>value</node>当成两层结点
                } else if(node.getNodeName().equals("jdbcurl")) {
                    jdbcUrl = node.getFirstChild().getNodeValue();
                } else if(node.getNodeName().equals("dbuser")) {
                    dbUser = node.getFirstChild().getNodeValue();
                } else if(node.getNodeName().equals("dbpwd")) {
                    dbPwd = node.getFirstChild().getNodeValue();
                }
            }
        }
    }

    public String getDbPwd() {
        return dbPwd;
    }

    public String getDbUser() {
        return dbUser;
    }

    public String getJdbcDriver() {
        return jdbcDriver;
    }

    public String getJdbcUrl() {
        return jdbcUrl;
    }

}

DB.java

/**
 * 功能:连接、关闭数据库
 */
package db;

import java.io.IOException;
import java.sql.*;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

public class DB {
    private DBConfig config = null;
    private Connection conn = null;

    public DB() throws ClassNotFoundException, ParserConfigurationException, SAXException, IOException {
        config = new DBConfig();
        Class.forName(config.getJdbcDriver());
    }

    public Connection getConnection() throws SQLException {
        conn = DriverManager.getConnection(config.getJdbcUrl(), config.getDbUser(), config.getDbPwd());
        return conn;
    }

    public void close() throws SQLException {
        if(conn != null)
            conn.close();
    }
}

DBBak.java

/**
 * 功能:备份、还原数据库
 */
package db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Calendar;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

public class DBBak {
    private DBConfig config = null;

    public DBBak() throws ParserConfigurationException, SAXException, IOException {
        config = new DBConfig();
    }

    public String getFileName() {
        Calendar today = Calendar.getInstance();
        String year = String.valueOf(today.get(Calendar.YEAR));
        String month = String.valueOf(today.get(Calendar.MONTH) + 1);//0~11表示1~12月
        String date = String.valueOf(today.get(Calendar.DATE));
        String time = String.valueOf(today.getTimeInMillis());
        return year + "-" + month + "-" + date + "-" + time + ".sql";
    }
   
    public void backUp(String path) {
        try {
            String jdbcUrl = config.getJdbcUrl();
            int pos = jdbcUrl.lastIndexOf("/");
            String dbName = jdbcUrl.substring(pos+1);
            String cmd = "mysqldump -u" + config.getDbUser() + " -p" + config.getDbPwd() + " " + dbName;
            Runtime rt = Runtime.getRuntime();
            Process child = rt.exec(cmd);
            InputStream in = child.getInputStream();
            InputStreamReader xx = new InputStreamReader(in, "ISO-8859-1");
            String inStr;
            StringBuffer sb = new StringBuffer("");
            String outStr;
            BufferedReader br = new BufferedReader(xx);
            while ((inStr = br.readLine()) != null) {
                sb.append(inStr + "\r\n");
            }
            outStr = new String(sb.toString().getBytes("ISO-8859-1"), "UTF-8");
            FileOutputStream fout = new FileOutputStream(path);
            OutputStreamWriter writer = new OutputStreamWriter(fout,"UTF-8");
            writer.write(outStr);
            writer.flush();
            in.close();
            xx.close();
            br.close();
            writer.close();
            fout.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void load(String path){
        try{
            File f = new File(path);
            FileInputStream fis = new FileInputStream(f);
            String jdbcUrl = config.getJdbcUrl();
            int pos = jdbcUrl.lastIndexOf("/");
            String dbName = jdbcUrl.substring(pos+1);
            String cmd = "mysql -u" + config.getDbUser() + " -p" + config.getDbPwd() + " " + dbName;
            Runtime rt = Runtime.getRuntime();
            Process child = rt.exec(cmd);
            OutputStream out = child.getOutputStream();
            String inStr;
            StringBuffer sb = new StringBuffer("");
            String outStr;
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
            while ((inStr = br.readLine()) != null) {
                sb.append(inStr + "\r\n");
            }
            outStr =new String(sb.toString().getBytes("UTF-8"), "ISO-8859-1");
            OutputStreamWriter writer = new OutputStreamWriter(out, "ISO-8859-1");
            writer.write(outStr);
            writer.flush();
            out.close();
            br.close();
            writer.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

FileList.java

/**
 * 功能:列出数据库备份文件
 */
package db;

import java.io.File;
import java.util.ArrayList;

public class FileList {
    public ArrayList tree(File f) {//传入目录
        ArrayList files = new ArrayList();
        File[] list = f.listFiles();
        if(list != null){
            for(int i = 0; i < list.length; i++) {
                if(list[i].isFile()) {
                    if(list[i].getName().endsWith(".sql")) {
                        files.add(list[i].getName());
                    }
                }
            }
        }
        return files;
 }
}