尝试更新“ PRAGMA user_version;”但不更新

时间:2019-03-04 02:01:36

标签: java jdbc sqlite

我正在尝试实现数据库版本控制系统,以便将来可以将内容添加/删除到各种表模式中。但是,我可以读取数据库的pragma user_version,但是我尝试写入该数据库的所有操作都失败了……我已经花了大约2个小时,但没有成功。这是我目前所在的位置: '包statusboard.databaseHelpers;

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

public class DataBaseHelper {

    Connection c = null;
    static Constants con = new Constants();
    static int version = -1;

    public DataBaseHelper() {
        openDatabase();
    }

    public DataBaseHelper(Connection con) {
        c = con;
    }

    public void openDatabase() {
        try {
            Class.forName("org.sqlite.JDBC");
            c = DriverManager.getConnection(con.getDatabaseName());
        } catch (ClassNotFoundException | SQLException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(0);
        }
    }

    public int getDatabaseVersion() {
        // only call the SQL query if we have not already populated the version.
        if (version == -1) {
            if (c == null) {
                openDatabase();
            }
            try {
                Statement stmt = c.createStatement();
                ResultSet result;
                String sql = "PRAGMA user_version;";
                result = stmt.executeQuery(sql);
                while (result.next()) {
                    version = result.getInt(1);
                }
                stmt.close();
            } catch (SQLException e) {
                System.err.println(e.getClass().getName() + ": " + e.getMessage());
            }
        }
        System.out.println("Returning version: " + version);
        return version;
    }

    public int incrementDatabaseVersion() {
        if (c == null) {
            openDatabase();
        }
        // ensure version has been populated
        if (version == 0) {
            getDatabaseVersion();
        }
        version++;
        System.out.println("new version: " + version);
        try {
            c.createStatement().execute("PRAGMA user_version =  21;");
            //stmt.execute("PRAGMA user_version = " + version);
            System.out.println("After execute");

        } catch (SQLException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
        return version;
    }

}

'

Constants.java当然会返回一个有效的数据库。

1 个答案:

答案 0 :(得分:0)

您可能需要清理SQLite数据库文件。看看真空here