当前位置: 代码迷 >> java >> 尝试更新“ PRAGMA user_version;” 但不更新
  详细解决方案

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

热度:65   发布时间:2023-07-26 14:14:19.0

我正在尝试实现数据库版本控制系统,以便将来可以在各种表模式中添加/删除内容。 但是,我可以读取数据库的pragma user_version,但是我尝试写入该数据库的所有操作都失败了……我已经花了大约2个小时,但没有成功。 我现在在这里:'package 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当然会返回一个有效的数据库。

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