【问题标题】:Paste comma separated list into EditText and store in SQLite TABLE on multiple rows将逗号分隔的列表粘贴到 EditText 并存储在 SQLite TABLE 中的多行
【发布时间】:2019-03-11 14:33:24
【问题描述】:

我想知道如何将逗号分隔的列表 (test1,test2,test3,test4) 粘贴到 EditText 字段中,然后单击按钮将其存储在我的 SQLite 数据库表中,每个表都在它自己的行中。这将是理想的,以便拥有大列表(50-100)的人可以大量插入数据。现在我有它,它会在我的表中插入一个名称。

DatabaseHelper.java

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String TAG = "DatabaseHelper";

    private static final String TABLE_NAME = "hashtag_table";
    private static final String COL1 = "ID";
    private static final String COL2 = "name";

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
        onCreate(db);
    }


    public DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    /**
     * Add data to the table
     * @param item
     * @return
     */
    public boolean addData(String item) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item);

        Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);

        long result = db.insert(TABLE_NAME, null, contentValues);

        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Gets the data from the table
     * @return
     */
    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    /**
     * Gets the ID from the table
     * @param name
     * @return
     */
    public Cursor getItemID(String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + COL1 + " FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
        Cursor data = db.rawQuery(query,null);
        return data;
    }

    /**
     * Updates the name from the table
     * @param newName
     * @param id
     * @param oldName
     */
    public void updateName(String newName, int id, String oldName) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE " + TABLE_NAME + " SET " + COL2 + " = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" + " AND " + COL2 + " = '" + oldName + "'";
        Log.d(TAG, "updateName: query: " + query);
        Log.d(TAG, "updateName: setting name to " + newName);
        db.execSQL(query);
    }

    /**
     * Deletes the name from the table
     * @param id
     * @param name
     */
    public void deleteName(int id, String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "DELETE FROM " + TABLE_NAME + " WHERE " + COL1 + " = '" + id + "'" + " AND " + COL2 + " = '" + name + "'";
        Log.d(TAG, "deleteName: query: " + query);
        Log.d(TAG, "deleteName: Deleting " + name + " from database.");
        db.execSQL(query);
        db.execSQL("UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE NAME = '"+TABLE_NAME+"'");
    }
}

ListView.java(editText 和按钮现在所在的位置)

//Adds new hashtag to list and prompts if nothing is entered
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String newEntry = editText.getText().toString();

            if (editText.length() != 0) {
                addData(newEntry);
                editText.setText("");
            } else {
                toastMessage("you must put something in the text field");
            }
        }
    });

    populateListView();
}

/**
 * Adds new data into the Database
 * @param newEntry
 */
public void addData(String newEntry) {
    boolean insertData = mDatabaseHelper.addData(newEntry);

    if (insertData) {
        toastMessage("Successfully inserted");
        recreate();
    } else {
        toastMessage("Whoops, something went wrong");
    }
}

【问题讨论】:

  • 顺便说一句,您的代码对 SQL 注入并不安全。
  • @Zoe 实际上它受到 SQL 注入的保护,(转义),作为底层 SQL 的插入便捷方法构造的一部分。

标签: java android sqlite android-sqlite


【解决方案1】:

以下是 addData 的一个非常基本的替换,它使用字符串的 split 方法将字符串分解为逗号分隔值并插入它们:-

/**
 * Add data to the table
 *
 * @param item
 * @return
 */
public boolean addData(String item) {

    String[] splitdata = item.split(","); //<<<<<<<<<< split the input string
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    boolean result = true;
    db.beginTransaction(); //<<<<<<<<<< prepare to do in a single transaction
    // Loop through each string inserting an entry into the database
    for (String s : splitdata) {
        contentValues.clear(); //<<<<<<<<<< clear any existing values to be safe
        contentValues.put(COL2, s);
        if (db.insert(TABLE_NAME, null, contentValues) < 1) {
            result = false;
        }
    }
    if (result) {
        db.setTransactionSuccessful(); //<<<<<<<<<< only set the transaction successful if all inserts worked
    }
    db.endTransaction();
    return result;
}

请注意,如果有任何插入失败,这将回滚所有插入并另外返回 false。

  • 以上代码为原理代码,未经测试或运行,可能存在一些错误。

【讨论】:

  • 你太棒了!这非常有效。非常感谢!
  • @NobleFins 很好,如果您认为答案帮助您解决了问题,请勾选答案。
  • 你明白了!再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 2011-05-30
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
相关资源
最近更新 更多