跳转到内容

Java JDBC 使用 SQLite/示例基类

来自维基教科书,开放的书籍,为开放的世界

此页面提供了一个示例基类,您可以将其用作创建自己的基类的骨架,以及扩展此类的思路。您应该注意,您主要的关注点应该是正确地设置初始上下文,并且有许多不同的方法来解决这个问题。此基类是抽象的,因为我们希望将其扩展以更精确地满足我们的需求。但是,其中没有任何特别深奥的东西来阻止您通过声明它为 public 并直接使用它来具体化此类,并相应地修改和提供您自己的构造函数。

您还应该注意,此基类中有一些声明为 public 的字段和方法,这些字段和方法更适合声明为 private,但是这些字段和方法被保留为 public 用于可见性,因为您可能希望尝试一些调用的含义。此外,将这些字段和方法保留为 public 使您能够通过反射来调用和调整它们。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


/** Database connection class & utilities **/

abstract class Db {

    public  String sDriver = ""; 
    public  String sUrl = null;
    public  int iTimeout = 30;
    public  Connection conn = null;
    public  Statement statement = null;


    /* Stub constructor for quick instantiation o/t fly for using some of the ancillary stuff */

    public  Db()
    {}

    /* quick and dirty constructor to test the database passing the DriverManager name and the fully loaded url to handle */
    /* NB this will typically be available if you make this class concrete and not abstract */
    public Db(String sDriverToLoad, String sUrlToLoad) throws Exception
    {
        init(sDriverToLoad, sUrlToLoad);
    }
    
    public void init(String sDriverVar, String sUrlVar) throws Exception
    {
        setDriver(sDriverVar);
        setUrl(sUrlVar);
        setConnection();
        setStatement();
    }

    private void setDriver(String sDriverVar)
    {
        sDriver = sDriverVar;
    }

    private void setUrl(String sUrlVar)
    {
        sUrl = sUrlVar;
    }

    public  void setConnection() throws Exception {
        Class.forName(sDriver);
        conn = DriverManager.getConnection(sUrl);
    }


    public  Connection getConnection() {
        return conn;
    }

    public  void setStatement() throws Exception {
        if (conn == null) {
            setConnection();
        }
        statement = conn.createStatement();
        statement.setQueryTimeout(iTimeout);  // set timeout to 30 sec.
    }

    public  Statement getStatement() {
        return statement;
    }

    public  void executeStmt(String instruction) throws SQLException {
        statement.executeUpdate(instruction);
    }

    // processes an array of instructions e.g. a set of SQL command strings passed from a file
    //NB you should ensure you either handle empty lines in files by either removing them or parsing them out 
    // since they will generate spurious SQLExceptions when they are encountered during the iteration....
    public void executeStmt(String[] instructionSet) throws SQLException {
        for (int i = 0; i < instructionSet.length; i++) {
            executeStmt(instructionSet[i]);
        }
    }

    public ResultSet executeQry(String instruction) throws SQLException {
        return statement.executeQuery(instruction);
    } 

    public void closeConnection() {
        try { conn.close(); } catch (Exception ignore) {}
    }

}
华夏公益教科书