package xyz.wbsite.wsqlite;

import java.io.File;
import java.sql.*;

/**
 * xyz.wbsite.wsqlite.Client
 *
 * @author wangbing
 */
public class Client {

    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String dbFilePath;

    /**
     * 构造函数
     *
     * @param dbFile 文件
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public Client(File dbFile) throws ClassNotFoundException, SQLException {
        this.dbFilePath = dbFile.getAbsolutePath();
        if (!dbFile.exists()) {
            connection = getConnection();
        }
    }

    /**
     * 执行sql语句
     *
     * @param sql
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public void execute(String sql) throws SQLException, ClassNotFoundException {
        try {
            getStatement().execute(sql);
        } finally {
            destroyed();
        }
    }

    /**
     * 执行sql查询语句
     *
     * @param sql
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public ResultSet executeQuery(String sql) throws SQLException, ClassNotFoundException {
        return getStatement().executeQuery(sql);
    }

    /**
     * 执行sql更新语句
     *
     * @param sqls
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public int executeUpdate(String... sqls) throws SQLException, ClassNotFoundException {
        int count = 0;
        try {
            for (String sql : sqls) {
                count += getStatement().executeUpdate(sql);
            }
        } finally {
            destroyed();
        }
        return count;
    }

    /**
     * 获取数据库连接
     *
     * @return 数据库连接
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    Connection getConnection() throws ClassNotFoundException, SQLException {
        if (null == connection) {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:" + dbFilePath);
        }
        return connection;
    }

    /**
     * 获取数据库Statement对象
     */
    Statement getStatement() throws SQLException, ClassNotFoundException {
        if (null == statement) {
            statement = getConnection().createStatement();
        }
        return statement;
    }

    /**
     * 数据库资源关闭和释放
     */
    public void destroyed() {
        try {
            if (null != resultSet) {
                resultSet.close();
                resultSet = null;
            }

            if (null != statement) {
                statement.close();
                statement = null;
            }
            if (null != connection) {
                connection.close();
                connection = null;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}