我尝试连接SQLite。
public class Database {
private Statement stmt;
private Connection conn;
private final String DB_NAME = "db.sqlite";
private final String DB_PATH = "/data/data/com.Simple_Diary/databases/";
public void Database()
{
connect();
}
/**
* Connect to the database
*/
public void connect()
{
try {
copyDataBase();
Class.forName("org.sqlite.JDBC").newInstance();
conn = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH + DB_NAME);
stmt = conn.createStatement();
}
catch (Exception e) {}
}
/**
* Query
* @param sql
* @return ResultSet Result object
*/
public ResultSet query(String sql)
{
try {
return stmt.executeQuery(sql);
}
catch (SQLException | NullPointerException e) {
return null;
}
}
/**
* Copy database file from assets to "databases" directory
*/
private void copyDataBase()
{
try {
MainActivity ma = new MainActivity();
InputStream mInput = ma.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0){
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
catch (IOException e) {}
}
}
try {
Database db = new Database();
ResultSet rs = db.query("SELECT * FROM categories");
String str = "its null!";
if(rs != null) {
while (rs.next()) {
str += rs.getString("title") + "\n";
}
}
dbtext.setText(str);
} catch(SQLException e){
dbtext.setText("err: " + e.toString());
}
但变量“rs”返回null,因为变量“conn”返回null。我在这个网站上为同样的问题读了很多答案,但我无法解决这个问题...... 我正在使用intelliJ。我添加了sqlite-jdbc jar作为库,但它没有帮助。
答案 0 :(得分:0)
您应该使用SQLiteOpenHelper类。这封装了很多工作。您需要做的就是
@Override
public void onCreate(SQLiteDatabase db)
{
// put DDL here to create and init your tables, if needed.
}
然后使用insertOrThrow或rawQuery(query,args)等方法。
如果您需要更多帮助,请与我联系。