Android-based SQLite database insert operation

Source: Internet
Author: User

Prototype:

Long Android. database. SQLite. sqlitedatabase. insert (string table, string nullcolumnhack, contentvalues values)

 

Parameter introduction:

Table: Name of the table to insert data

Nullcolumnhack: When the values parameter is null or there is no content in it, insert will fail (the underlying database cannot insert a blank row). To prevent this, we need to specify a column name here. If we find that the row to be inserted is empty, we will set the value of this column name to null and then insert it to the database.

Values: A contentvalues object, similar to a map. Stores values in the form of key-value pairs.

 

Many people may wonder why nullcolumnhack is used. When we do not set a column, aren't all databases set as default values? The default values of many fields are also null. The settings shown here are also null. What is the difference? How can I enable the settings to be inserted?

In fact, at the underlying layer, all the insert Methods finally go back and call the insertwithonconflict method. Here we paste some implementations of this method.

 

[java] view plaincopy/**     * General method for inserting a row into the database.     *     * @param table the table to insert the row into     * @param nullColumnHack SQL doesn't allow inserting a completely empty row,     *            so if initialValues is empty this column will explicitly be     *            assigned a NULL value     * @param initialValues this map contains the initial column values for the     *            row. The keys should be the column names and the values the     *            column values     * @param conflictAlgorithm for insert conflict resolver     * @return the row ID of the newly inserted row     * OR the primary key of the existing row if the input param 'conflictAlgorithm' =     * {@link #CONFLICT_IGNORE}     * OR -1 if any error     */     public long insertWithOnConflict(String table, String nullColumnHack,             ContentValues initialValues, int conflictAlgorithm) {         if (!isOpen()) {             throw new IllegalStateException("database not open");         }           // Measurements show most sql lengths <= 152         StringBuilder sql = new StringBuilder(152);         sql.append("INSERT");         sql.append(CONFLICT_VALUES[conflictAlgorithm]);         sql.append(" INTO ");         sql.append(table);         // Measurements show most values lengths < 40         StringBuilder values = new StringBuilder(40);           Set<Map.Entry<String, Object>> entrySet = null;         if (initialValues != null && initialValues.size() > 0) {             entrySet = initialValues.valueSet();             Iterator<Map.Entry<String, Object>> entriesIter = entrySet.iterator();             sql.append('(');               boolean needSeparator = false;             while (entriesIter.hasNext()) {                 if (needSeparator) {                     sql.append(", ");                     values.append(", ");                 }                 needSeparator = true;                 Map.Entry<String, Object> entry = entriesIter.next();                 sql.append(entry.getKey());                 values.append('?');             }               sql.append(')');         } else {             sql.append("(" + nullColumnHack + ") ");             values.append("NULL");         }  

We can see that when initialvalues of the contentvalues type is null or size <= 0, nullcolumnhack is added to the SQL statement. We can imagine that if we do not add nullcolumnhack, the final result of our SQL statement will be similar to insert into tablename () values (); this is obviously not allowed. If we add nullcolumnhack, the SQL statement will become like this. insert
Tablename (nullcolumnhack) values (null); this obviously works.

 

The insert operation method code is attached below:

public void insert(String name, String address, String type, String notes) {ContentValues cv=new ContentValues();cv.put("name", name);cv.put("address", address);cv.put("type", type);cv.put("notes", notes);getWritableDatabase().insert("restaurants", "name", cv);}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.