Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to establish Database in Android SQLite3 Foundation

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Android SQLite3 foundation of how to build a database, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Background

SQLite is a very popular embedded database, it provides a refreshing SQL interface, quite small memory footprint and high-speed response, more Happy is that it is free, everyone can enjoy the use, many awesome companies (such as Adobe,Apple,Google,Sun,Symbian), open source projects (Mozilla,PHP,Python) are in the product assembly SQLite.

SQLite3 feature

Comparison with traditional relational database

There are:

Sql statement: SELECT INSERT UPDATE

CREATE DROP

Data type:

Case insensitive

TEXT text

NUMERIC value

INTEGER integer

REAL decimal

NONE is untyped

There are no:

FOREIGN KEY foreign key constraint

RIGHT OUTER JOIN and FULL OUTER JOIN

ALTER TABLE

Start to do it.

Before you start, make sure that the following environment is configured on your machine:

Android development environment (how to configure Google, there are many)

This document applies to the environment Android 1.0

1. Build the database

Method 1: command line mode (suitable for debugging)

You can use adb shell to enter the device backend and create it manually on the command line, as follows:

After starting the simulator in Eclipse, enter it into the device Linux console under cmd

D:\ > adb shell

After that, enter the application data directory

# cd / data/data

Ls list directory, check the files, find your project directory and enter

Check to see if there is a databases directory, and if not, create a

# mkdir databases

Cd databases enters and creates the database

# sqlite3 friends.db

Sqlite3 friends.db

SQLite version 3.5.9

Enter ".help" for instructions

Sqlite >

Ctrl+d exits the sqlite prompt ls list directory to see that a file has been created friends.db

He is the library file of SQLite.

# ls

Ls

Friends.db

Method 2: coding method (use more)

Functions are provided in android.content.Context. Note: Activity is a subclass of Context

OpenOrCreateDatabase () to create our database

Db = context .openOrCreateDatabase (

String DATABASE_NAME, int Context. MODE_PRIVATE, null)

The name of the String DATABASE_NAME database

Int MODE operation mode Context.MODE_PRIVATE, etc.

CursorFactory pointer factory. In this example, null is passed, which is not used for the time being.

2, create a table

Command line mode

# sqlite3

Sqlite > create table widgets (id integer primary key autoincrement,name text)

3, insert data

Increased command line, querying data

Sqlite > insert into widgets values (null,'tom')

Insert into widgets values (null,'tom')

Sqlite > select * from widgets

Select * from widgets

1 | tom

Sqlite >

API mode

Package org.imti; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView / * SQLite Demo * * databases for private access by Activity do not use ContentProvider to add query data * * @ author daguangspecial@gmail.com * * / public class DbDemo extends Activity {EditText inputTxt; Button btnAdd; Button btnViewAll; TextView viewAll; DBHelper db @ Override protected void onCreate (Bundle savedInstanceState) {/ / TODO Auto-generated method stub super.onCreate (savedInstanceState); this.setContentView (R.layout.dbdemo); / / initialize UI btnAdd = (Button) findViewById (R.id.btnAdd); btnViewAll = (Button) findViewById (R.id.btnViewAll); viewAll = (TextView) findViewById (R.id.viewAll) InputTxt = (EditText) findViewById (R.id.txtInput); / / initialize DB db = new DBHelper (this) / / initialize listening OnClickListener listener = new OnClickListener () {public void onClick (View v) {if (v.getId () = = R.id.btnAdd) {/ / add db.save (inputTxt.getText () .toString ()) Db.close ();} else if (v.getId () = = R.id.btnViewAll) {/ / browse all data Cursor cur = db.loadAll (); StringBuffer sf = new StringBuffer (); cur.moveToFirst () While (! cur.isAfterLast ()) {sf.append (cur.getInt (0)) .append (":") .append (cur.getString (1)) .append ("\ n"); cur.moveToNext () } db.close (); viewAll.setText (sf.toString ());}; btnAdd.setOnClickListener (listener); btnViewAll.setOnClickListener (listener);}}

Java code

Package org.imti; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; / * Database manipulation tool class * * @ author daguangspecial@gmail.com * * / public class DBHelper {private static final String TAG = "DBDemo_DBHelper"; / / Debug tag private static final String DATABASE_NAME = "dbdemo.db" / / Database name SQLiteDatabase db; Context context;// application environment context Activity is its subclass DBHelper (Context _ context) {context = _ context;// Open database db = context.openOrCreateDatabase (DATABASE_NAME, Context.MODE_PRIVATE,null); CreateTable () Log.v (TAG, "db path=" + db.getPath ());} / * * build table * column names are case sensitive? * what data types do you have? * SQLite 3 * TEXT text NUMERIC numeric INTEGER integer REAL decimal NONE untyped * query whether to send select? * / public void CreateTable () {try {db.execSQL ("CREATE TABLE t_user (" + "_ ID INTEGER PRIMARY KEY autoincrement) "+" NAME TEXT "+") "); Log.v (TAG," Create Table t_user ok ");} catch (Exception e) {Log.v (TAG," Create Table t_user err,table exists. ") }} / * add data * @ param id * @ param uname * @ return * / public boolean save (String uname) {String sql= "; try {sql=" insert into t_user values (null,' "+ uname+") "; db.execSQL (sql) Log.v (TAG, "insert Table t_user ok"); return true;} catch (Exception e) {Log.v (TAG, "insert Table t_user err, sql:" + sql); return false }} / * query all records * * @ return Cursor pointer to the result record, similar to JDBC's ResultSet * / public Cursor loadAll () {Cursor cur=db.query ("t_user", new String [] {"_ ID", "NAME"}, null,null, null,null, null) Return cur;} public void close () {db.close ();}}

Screenshot:

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report