SQLite连接w / Libgdx .Desktop

时间:2016-06-10 17:19:20

标签: java sqlite libgdx

好吧,我正试图在我的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和连接类..

1 个答案:

答案 0 :(得分:0)

在将数据库与应用程序一起使用时,我通常会做一个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可以输出到我们数据库的连接。现在,当我们想要与数据库交互时,您可以适当地获得连接。在你的主要内部,它可能看起来像这样:

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数据库中创建表并插入记录,然后才能进行任何交互,所以请记住这一点。