以编程方式手动将数据插入sqlite表

时间:2018-03-31 10:19:09

标签: android android-sqlite android-studio-3.0

如何以编程方式将数据输入/插入sqlite数据库。我搜索了类似的问题,但我看到的只是使用cmd或SDK工具来执行此操作。

这是我的主要活动: -

public class MainActivity extends AppCompactActivity {

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    SQLiteDatabase db;

    db = openOrCreateDatabase("books.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);

    final String CREATE_BOOKS_TABLE = "CREATE TABLE IF NOT EXISTS book_list ("
            + "id INTEGER primary key AUTOINCREMENT,"
            + "name,"
            + "genre,"
            + "description,"
            + "created_at TIMESTAMP,"")";
    db.execSQL(CREATE_BOOKS_TABLE);

我想做类似的事情:

    insert into books.db values (null, "Wheel of Time.epub", "fantasy", " Its absolutely the best", "2017-02-13 13:11:06");

有什么方法可以做到吗?

2 个答案:

答案 0 :(得分:1)

您已创建表的列而未指定其类型。它应该是

final String CREATE_BOOKS_TABLE = "CREATE TABLE IF NOT EXISTS book_list ("
        + "id INTEGER primary key AUTOINCREMENT,"
        + "name TEXT,"
        + "genre TEXT,"
        + "description TEXT,"
        + "created_at TIMESTAMP)";

对于Insert,您可以使用:

        String sql =
        "INSERT or replace INTO book_list (name, genre, description, created_at) VALUES('Wheel of Time.epub','fantasy','Its absolutely the best','2017-02-13 13:11:06')" ;       
        db.execSQL(sql);

<强>更新

您可以声明created_at列在插入时默认获取其值,如下所示:

final String CREATE_BOOKS_TABLE = "CREATE TABLE IF NOT EXISTS book_list ("
        + "id INTEGER primary key AUTOINCREMENT,"
        + "name TEXT,"
        + "genre TEXT,"
        + "description TEXT,"
        + "created_at TIMESTAMP not null default current_timestamp)";

然后你在插入时不需要为它设置一个值:

        String sql =
        "INSERT or replace INTO book_list (name, genre, description) VALUES('Wheel of Time.epub','fantasy','Its absolutely the best')" ;       
        db.execSQL(sql);

答案 1 :(得分:1)

这是一个非常通用的问题,但我可以想到的最简单的方法,而不进入课程:

  1. 将Edittext和按钮拖到活动中。
  2. 将按钮附加到Edittext以将数据转换为字符串。
  3. 使用上面的insert语句将数据放入数据库。
  4. 编辑,此代码是否可以帮助您进行MainActivity:

    import android.database.sqlite.SQLiteDatabase;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
    EditText etName;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final SQLiteDatabase db = this.openOrCreateDatabase("books.db", MODE_PRIVATE, null);// Open or Create Database if none exists
    
        final String CREATE_BOOKS_TABLE = "CREATE TABLE IF NOT EXISTS book_list ("
                + "id INTEGER primary key AUTOINCREMENT,"
                + "name TEXT,"
                + "genre TEXT,"
                + "description TEXT)";
        db.execSQL(CREATE_BOOKS_TABLE); // Creates the fields for the database
    
        Button btnData=findViewById(R.id.btnInsertData); // finds the button
        etName=findViewById(R.id.etName); // Our text input box
    
    // Set an OnClickListener for the button so when it's clicked, the code below is triggered  
        btnData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String nameTxt=etName.getText().toString();
                db.execSQL("INSERT INTO book_list (name, genre, description) VALUES ('"+nameTxt+"', 'fantasy', 'review')"); // Inserts the nameTxt data from the text box into the database, the other fields remain the same 
                Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show();// Makes a Toast to show the data is inserted
                etName.setText("");// Clears the Textbox
            }
        });
    }
    

    }

    您的Xml文件:

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    
    <Button
        android:id="@+id/btnInsertData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Insert"/>
    
    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Name" />
    </LinearLayout>
    

    这将为您的数据库创建一个输入字段。它不是干净的代码或最好的方法,但它很简单,并演示了如何获取文本输入并将其放入数据库。