我正在尝试在动态Web项目
中使用Sqlite db
。我正在使用sqlite4java让java连接到数据库。我已经创建了一个 db 文件,现在尝试从我的动态 Web 项目访问它。代码是这样的 -
StringBuilder res = new StringBuilder();
SQLiteConnection db = null;
SQLiteStatement st = null;
try {
db = new SQLiteConnection(new File("dbfile.dbf"));
db.open();
st = db.prepare("SELECT * FROM tbl_Tblsignscores");
// st.bind(1, minimumQuantity);
while (st.step()) {
res.append(String.format("ID: %d, Score: %d \n",
st.columnInt(0), st.columnInt(1)));
// orders.add(st.columnLong(0));
}
} catch (Exception ex) {
} finally {
st.dispose();
db.dispose();
}
return res.toString();
但连接总是在 db.open()
处失败。它显示 NullpointerException。我尝试将 dbfile 放入项目根目录的 web-inf>lib
、web-int
中,但似乎没有任何效果。谁能指出我正确的方向?
最佳答案
我也很喜欢你的问题。我用自己的解决方案修复了它,但我不确定这是一个好的解决方案。解决方案是使用类路径
。
Web应用程序目录结构
- app-root
- WEB-INF
- classes
- mydb.db
程序
protected Connection getConnection() {
Connection con = null;
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:" + this.getClass().getResource("/").getPath() + "/mydb.db");
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return con;
}
现在,我不需要担心丢失 db
文件。它肯定在我的类路径目录中。
关于java - Java动态Web项目中的sqlite db文件保存在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20817417/