SQL查询方法返回null

时间:2016-01-23 11:49:44

标签: java jdbc

我有一个管理我的数据库的类。但是,由于我在课程static中创建了所有方法,因此查询方法不再有效:它返回null

这是DatabaseManager类:

public class DatabaseManager {
    public final static String DBPath = "database.db";
    private static Connection connection = null;
    private static Statement statement = null;

    /**
     * Connect to the database.
     * @return True if succeeded to connect to the database. False if not.
     */
    private static boolean connect() {
        try {
            Class.forName("org.sqlite.JDBC");
            connection = DriverManager.getConnection("jdbc:sqlite:" + DBPath);
            statement = connection.createStatement();
            return true;
        }
        catch (ClassNotFoundException | SQLException connectException) {
            connectException.printStackTrace();
            System.out.println("Unable to connect to the database.");
            return false;
        }
    }

    /**
     * Close the connection.
     */
    private static void close() {
        try {
            connection.close();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * Execute a query inside a database.
     * @param queryStr the SQL query
     * @return ResultSet object is the result of the query (if it succeeded)
     */
    public static ResultSet query(String queryStr) {
        connect();
        ResultSet result = null;

        try {
            result = statement.executeQuery(queryStr);
        }
        catch (SQLException e) {
            e.printStackTrace();
            System.out.println("Impossible to execute the following query : " + queryStr);
            System.out.println("It may contains error.");
        }
        finally {
            close();
        }

        return result;

    }
}

当我将其添加到query方法时:

try {
    while(result.next()) {
        System.out.println(result.getString("columnTest"));
    }
}
catch (SQLException e) { e.printStackTrace(); }

我在终端上取得了不错的成绩。 (数据来自数据库)。但当我删除它,并将其添加到main方法:

import DatabaseManager;

import java.sql.ResultSet;
import java.sql.SQLException;

public class Main {

    public static void main(String[] args) {
        ResultSet result;
        result = DatabaseManager.query("SELECT * FROM DataTest");

        try {
            while (result.next()) {
                System.out.println(result.getString("columnTest"));
            }
        }
        catch (SQLException e) {
            e.getStackTrace();
        }
    }
}

打印null,好像查询没有返回任何内容......为什么会这样?

1 个答案:

答案 0 :(得分:0)

我认为问题来自你的功能"查询"。你正在关闭那里的连接。因此,您无法在主

中打印结果