【问题标题】:SQLite connection w/ Libgdx .Desktop带有 Libgdx .Desktop 的 SQLite 连接
【发布时间】:2016-06-10 17:19:20
【问题描述】:

嗯,我正在尝试在我的 Libgdx 游戏中使用 SQLite,但不知道如何。

public class Main { public static void main(String[] args){ LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = Game.TITLE; config.width = Game.V_WIDTH * Game.SCALE; config.height = Game.V_HEIGHT * Game.SCALE; new LwjglApplication(new Game(), config); }}

我主要需要做什么?哈哈 我一直在寻找这个,但我能找到的都是与 Android 应用程序有关的。

I already have the driver in my ref libraries,以及连接类..

【问题讨论】:

  • 制作游戏不仅仅是制作游戏。了解 Java,知道如何使用其他库,从这些库中读取 API。如果没有这个,你会发现制作视频游戏非常困难、乏味和漫长的旅程。在 Java 中使用 SQLite 的方法有很多种,有很多库,每个库都有关于如何使用它们的教程以及 API 文档。
  • @Underbalanced 感谢您的回答!你是对的,但我认为我需要有人帮助我或链接一个教程,因为我找不到关于如何正确连接我的游戏与数据库的解释......我只是在这个库中找到与 android 相关的......跨度>
  • 当你得到一个连接的答案,那么你怎么知道如何使用它呢?数据不会神奇地保存到数据库中。您可能需要也可能不需要另一个库来帮助持久化它,或者您可能必须编写自己的所有持久性机制。我用谷歌搜索“使用 sqlite 和 java”,发现很多!这是第一个结果......这是列出的答案......SQLite Java Tutorial

标签: java sqlite libgdx


【解决方案1】:

在将数据库与应用程序一起使用时,我通常会创建一个 ConnectionFactory,它会返回与数据库的新连接。

public class ConnectionFactory {

   public static Connection getConnection() {
      Connection con = null;

      Class.forName("org.sqlite.JDBC");

      con = DriverManager.getConnection("jdbc:sqlite:test.db"); //change to whatever db you want

      return con;
   }
}

现在我们有一个 ConnectionFactory 可以抽出与我们数据库的连接。现在,当我们要与数据库交互时,您可以适当地获取连接。在你的 main 里面,它可能看起来像这样:

public static void main(String[] args) {
   Connection con = null;

   String firstName = null, lastName = null;

   try {
      con = ConnectionFactory.getConnection();
      PreparedStatement pstmt = con.prepareStatement("SELECT * FROM myTable where myId = ?");
      pstmt.setInt(1, /*some id here, ill put this as example:*/ 1234567);

      //execute the query and put into result set so we can get the values.
      ResultSet rs = pstmt.executeQuery();
      //the resultset iterates through rows, by calling next
      if( rs.next() ) //could be while(rs.next()) if expecting multiple rows
      { 
         firstName = rs.getString("firstName"); //column name you want to grab here
         lastName = rs.getString("lastName");
      }
   }  catch(SQLException sqle) {
      sqle.printStackTrace();
   }
   finally {
     try {
        con.close(); //dont forget to close your connection to database!
     } catch(SQLException sqle) {
        sqle.printStackTrace();
     }
   }
}

您需要在 SQLite 数据库中创建表并插入记录,然后才能进行任何交互,因此请记住这一点。

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 2012-02-07
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多