gpt4 book ai didi

java - 如何创建基于 ActionResolver 的 jdbc sqlite 连接?

转载 作者:行者123 更新时间:2023-11-30 01:12:23 26 4
gpt4 key购买 nike

我已按照维基 (https://code.google.com/archive/p/libgdx-users/wikis/SQLite.wiki) 上的说明进行操作,但我不确定如何实际使用数据库连接。我看过 http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm 的 jdbc 教程。我想我被困在连接上了。

解析器代码

public interface ActionResolver {
public Connection getConnection();
}

public class DesktopActionResolver implements ActionResolver {
public Connection getConnection() {
String url = "jdbc:sqlite:db.sqlite";
try {
Class.forName("org.sqlite.JDBC");
return DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}

public class AndroidActionResolver implements ActionResolver {

Handler uiThread;
Context appContext;

public AndroidActionResolver(Context appContext) {
uiThread = new Handler();
this.appContext = appContext;
}

@Override
public Connection getConnection() {
String url = "jdbc:sqldroid:/data/data/com.myapp/databases/db.sqlite";
try {
Class.forName("org.sqldroid.SQLDroidDriver").newInstance();
return DriverManager.getConnection(url);
} catch (InstantiationException e) {
Log.e("sql", e.getMessage());
} catch (IllegalAccessException e) {
Log.e("sql", e.getMessage());
} catch (ClassNotFoundException e) {
Log.e("sql", e.getMessage());
} catch (SQLException e) {
Log.e("sql", e.getMessage());
}
return null;
}
}

jdbc教程有

conn = DriverManager.getConnection(DB_URL,USER,PASS);

有人可以解释或指出有关如何使用 ActionResolvers 连接的正确方向吗?

为了让 conn 在我的其余代码中可用,我需要做什么?

我觉得应该是这样的

连接conn = ActionResolver.getConnection();

但事实并非如此。

最佳答案

经过反复试验和大量阅读后,我已经开始使用它了。这是代码

我的游戏.java

public class MyGame extends Game {
public ActionResolver actionResolver;

public MyGame(ActionResolver actionResolver) {
super();
this.actionResolver = actionResolver;
}

public void create() {
Connection conn = actionResolver.getConnection();
try {
Statement statment = conn.createStatement();
ResultSet resultSet = statment.executeQuery("select * from items");
while (resultSet.next())
{
System.out.println(resultSet.getString("name"));
}
} catch (Exception e) {
e.printStackTrace();
}
}

安卓启动器.java改变

initialize(new MyGame(), config);

initialize(new MyGame(new AndroidActionResolver(this.getBaseContext())), config);

DesktopLauncher.java改变

new LwjglApplication(new MyGame(), config);

new LwjglApplication(new MyGame(new DesktopActionResolver()), config);

关于java - 如何创建基于 ActionResolver 的 jdbc sqlite 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com