1.获取SQLiteDatabase对象db创建数据库或连接数据库:SQLiteDatabasedb = SQLiteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString()+ "/test.dbs", null);如果目录下有test.dbs数据库则是连接没有就是创建
2.用对象db的方法来执行sql语句:db.execSQL(String sql) 此方法木有返回值 所以查询不好弄。查询一般用db.rawQuery返回一个Cursor对象(相当与jdbc中的ResultSet),Cursor有如下几个方法来查询数据:
2.1 move ToFirst 将记录指针跳到第一行
2.2 moveToLast将记录指针跳到最后一行
2.3 moveNext将记录指针移到下一行
2.4moveToPosition( int ss)将记录指针跳到指定的ss行
2.5moveToPrevious将记录指针跳到上一行
将记录指针跳到指定的行之后就可以通过对象的getXXX方法来获取数据 :如 Cursor cursor = db.rawQuery("select na,pw from user where na=? and pw=?", new String []{name,pwd});
3.回收资源close
当然以SQLiteDatabase对象还可以调用许多方法来操作数据库,不过俺是觉得这几个方法基本够了
(仅此来练习SQLite的操作 一般注册的信息都样上传到服务器而不会是存储在手机数据库)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.android.xiong.sqlitelogin" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="14" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.android.xiong.sqlitelogin.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.android.xiong.sqlitelogin.RegistersActivity" android:label="@string/app_name" > </activity> </application> </manifest>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="30dp" android:gravity="center_horizontal" android:textColor="#8a2be2" android:textSize="35dp" android:text="登录界面" /> <TextView android:id="@+id/txtname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/login" android:layout_marginRight="5dp" android:layout_marginBottom="30dp" android:textSize="28dp" android:text="用户帐号:"/> <EditText android:id="@+id/edname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="30dp" android:layout_below="@id/login" android:layout_toRightOf="@id/txtname" android:layout_alignParentRight="true" android:hint="请输入用户帐号"/> <TextView android:id="@+id/txtpassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txtname" android:layout_marginRight="5dp" android:textSize="28dp" android:text="用户密码:"/> <EditText android:id="@+id/edpassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/edname" android:layout_toRightOf="@id/txtpassword" android:layout_alignParentRight="true" android:inputType="textPassword" android:hint="请输入用户密码"/> <LinearLayout android:layout_below="@id/edpassword" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:gravity="center_horizontal" > <Button android:id="@+id/btregister" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginRight="20dp" android:text="用户注册"/> <Button android:id="@+id/btlogin" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="用户登录"/> </LinearLayout> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/txt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="30dp" android:gravity="center_horizontal" android:text="注册界面" android:textColor="#8a2be2" android:textSize="35dp" /> <TextView android:id="@+id/txtname1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txt1" android:layout_marginBottom="30dp" android:layout_marginRight="5dp" android:text="帐号:" android:textSize="28dp" /> <EditText android:id="@+id/edname1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@id/txt1" android:layout_toRightOf="@id/txtname1" android:layout_marginBottom="30dp" /> <TextView android:id="@+id/txtpassword1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/txtname1" android:layout_marginRight="5dp" android:text="密码:" android:textSize="28dp" /> <EditText android:id="@+id/edpassword1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@id/edname1" android:layout_toRightOf="@id/txtpassword1" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/edpassword1" android:layout_marginTop="30dp" android:gravity="center_horizontal" android:orientation="horizontal" > <Button android:id="@+id/btregister1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:text="提交数据" /> </LinearLayout> </RelativeLayout>
package com.android.xiong.sqlitelogin; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { // 帐号和密码 private EditText edname; private EditText edpassword; private Button btregister; private Button btlogin; // 创建SQLite数据库 public static SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edname = (EditText) findViewById(R.id.edname); edpassword = (EditText) findViewById(R.id.edpassword); btregister = (Button) findViewById(R.id.btregister); btlogin = (Button) findViewById(R.id.btlogin); db = SQLiteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString() + "/test.dbs", null); // 跳转到注册界面 btregister.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(MainActivity.this, RegistersActivity.class); startActivity(intent); } }); btlogin.setOnClickListener(new LoginListener()); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); db.close(); } class LoginListener implements OnClickListener { @Override public void onClick(View v) { // TODO Auto-generated method stub String name = edname.getText().toString(); String password = edpassword.getText().toString(); if (name.equals("") || password.equals("")) { // 弹出消息框 new AlertDialog.Builder(MainActivity.this).setTitle("错误") .setMessage("帐号或密码不能空").setPositiveButton("确定", null) .show(); } else { isUserinfo(name, password); } } // 判断输入的用户是否正确 public Boolean isUserinfo(String name, String pwd) { try{ String str="select * from tb_user where name=? and password=?"; Cursor cursor = db.rawQuery(str, new String []{name,pwd}); if(cursor.getCount()<=0){ new AlertDialog.Builder(MainActivity.this).setTitle("错误") .setMessage("帐号或密码错误!").setPositiveButton("确定", null) .show(); return false; }else{ new AlertDialog.Builder(MainActivity.this).setTitle("正确") .setMessage("成功登录").setPositiveButton("确定", null) .show(); return true; } }catch(SQLiteException e){ createDb(); } return false; } } // 创建数据库和用户表 public void createDb() { db.execSQL("create table tb_user( name varchar(30) primary key,password varchar(30))"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
package com.android.xiong.sqlitelogin; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class RegistersActivity extends Activity { private EditText edname1; private EditText edpassword1; private Button btregister1; SQLiteDatabase db; @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); db.close(); } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.register); edname1 = (EditText) findViewById(R.id.edname1); edpassword1 = (EditText) findViewById(R.id.edpassword1); btregister1 = (Button) findViewById(R.id.btregister1); btregister1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String name = edname1.getText().toString(); String password = edpassword1.getText().toString(); if (!(name.equals("") && password.equals(""))) { if (addUser(name, password)) { DialogInterface.OnClickListener ss = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub // 跳转到登录界面 Intent in = new Intent(); in.setClass(RegistersActivity.this, MainActivity.class); startActivity(in); // 销毁当前activity RegistersActivity.this.onDestroy(); } }; new AlertDialog.Builder(RegistersActivity.this) .setTitle("注册成功").setMessage("注册成功") .setPositiveButton("确定", ss).show(); } else { new AlertDialog.Builder(RegistersActivity.this) .setTitle("注册失败").setMessage("注册失败") .setPositiveButton("确定", null); } } else { new AlertDialog.Builder(RegistersActivity.this) .setTitle("帐号密码不能为空").setMessage("帐号密码不能为空") .setPositiveButton("确定", null); } } }); } // 添加用户 public Boolean addUser(String name, String password) { String str = "insert into tb_user values(?,?) "; MainActivity main = new MainActivity(); db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString() + "/test.dbs", null); main.db = db; try { db.execSQL(str, new String[] { name, password }); return true; } catch (Exception e) { main.createDb(); } return false; } }