将文本框中的值插入 SQLite 数据库

发布于 2024-10-06 01:22:43 字数 92 浏览 0 评论 0原文

我创建了一个 Android 应用程序,它要求用户注册他的用户名和密码。我的问题是,如何将输入值(文本框)插入到我的 SQLite 数据库中?

提前致谢。

I've created an Android application which requires the user to register his username and password. My question is, how can I insert the input values(textbox) into my SQLite database?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绿光 2024-10-13 01:22:43

首先,如果您还没有http:,请阅读有关 SQLite 的 Android 文档: //developer.android.com/guide/topics/data/data-storage.html#db

然后假设你在数据库端正确设置了所有内容,下一步是构建你的 SQL,看起来像这样...

private static final String INSERT_SQL = "insert into " + TABLE + " (username, password) " + 
                                                      "   values    (?,        ?)";

然后你需要实际执行插入...

public void doInsert(String username, String password) {
    final SQLiteDatabase  db = getWritableDatabase();

    SQLiteStatement insert_stmt = null;

    try {
        insert_stmt = db.compileStatement(INSERT_SQL);

        insert_stmt.bindString(1,   username);
        insert_stmt.bindString(2,   password);
        insert_stmt.executeInsert();
    }
    finally {
        if (insert_stmt != null) insert_stmt.close();
    }
}

这假设 doInsert 位于扩展 SQLiteOpenHelper 的类中,所以它可以使用 getWritableDatabase,但只要你有 SQLiteOpenHelper,你就可以将 doInsert 移动到你喜欢的任何地方。

如果您需要从 EditText 获取值,那么这应该可以帮助您......

final EditText input = (EditText) findViewById(R.id.textId);
final String   txt   = input.getText().toString();

First, read Android docs on SQLite if you haven't already http://developer.android.com/guide/topics/data/data-storage.html#db.

Then assuming you have everything setup properly on the DB side the next step is to construct your SQL to look something like this...

private static final String INSERT_SQL = "insert into " + TABLE + " (username, password) " + 
                                                      "   values    (?,        ?)";

Then you need to actually do the insert...

public void doInsert(String username, String password) {
    final SQLiteDatabase  db = getWritableDatabase();

    SQLiteStatement insert_stmt = null;

    try {
        insert_stmt = db.compileStatement(INSERT_SQL);

        insert_stmt.bindString(1,   username);
        insert_stmt.bindString(2,   password);
        insert_stmt.executeInsert();
    }
    finally {
        if (insert_stmt != null) insert_stmt.close();
    }
}

This assumes doInsert is located in a class that extends SQLiteOpenHelper so that it can use getWritableDatabase, but as long as you have your SQLiteOpenHelper around you can move doInsert anywhere you like.

If you need to get values from an EditText then this should get you going...

final EditText input = (EditText) findViewById(R.id.textId);
final String   txt   = input.getText().toString();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文