码迷,mamicode.com
首页 > 数据库 > 详细

SQLlite实现增删查改

时间:2016-05-28 14:13:45      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

activity_main.xml文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="290dp"
        android:layout_height="wrap_content" 
        android:padding="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="手机号:"
            android:textSize="18sp" />

        <EditText
            android:id="@+id/ID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="290dp"
        android:layout_height="wrap_content" 
        android:padding="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="姓名:"
            android:textSize="18dp" />

        <EditText
            android:id="@+id/Name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </LinearLayout>

    <TextView
        android:id="@+id/StudentList"
        android:layout_width="290dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="显示数据" 
        android:padding="10dp"/>

</LinearLayout>

 

main.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/CreateDataBase"
        android:title="创建数据库">
    </item>
    <item
        android:id="@+id/CreateTable"
        android:title="创建表">
    </item>
    <item
        android:id="@+id/DropTable"
        android:title="删除表">
    </item>
    <item
        android:id="@+id/InsertData"
        android:title="插入数据">
    </item>
    <item
        android:id="@+id/ReadData"
        android:title="读取数据">
    </item>

</menu>

 

MainActivity.java

package com.zrdm.sqlitecrud;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    // 变量***********************************/
    private MyDataBase myDataBase = null;
    private String strSql = null;
    private EditText ID = null;
    private EditText Name = null;
    private TextView studentList = null;

    // 函数***********************************/

    // 创建
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        makeActionOverflowMenuShown();
        ID = (EditText) findViewById(R.id.ID);
        Name = (EditText) findViewById(R.id.Name);
        studentList = (TextView) findViewById(R.id.StudentList);        
    }

    // 创建菜单
    @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;
    }
/*
    // 创建表
    public void CreateTable(View v) {
        strSql = "Create table student(" + "ID nvarchar(20) not null,"
                + "Name nvarchar(40) not null," + "primary key(ID)" + " )";
        if (myDataBase == null) {
            myDataBase = new MyDataBase(this);
        }
        if (myDataBase.ExecSql(strSql)) {
            Toast.makeText(getApplicationContext(), "创建表成功!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "创建表失败!", Toast.LENGTH_SHORT).show();
        }

    }

    // 删除表
    public void DropTable(View v) {
        strSql = "Drop table student";
        if (myDataBase == null) {
            myDataBase = new MyDataBase(this);
        }
        if (myDataBase.ExecSql(strSql)) {
            Toast.makeText(getApplicationContext(), "删除表成功!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "删除表失败!", Toast.LENGTH_SHORT).show();
        }

    }

    // 插入数据
    public void InsertData(View v) {
        String strId = ID.getText().toString();
        String strName = Name.getText().toString();

        if (strId.equals("") || strName.equals("")) {
            Toast.makeText(getApplicationContext(), "学号或姓名不能为空!", Toast.LENGTH_SHORT).show();
        } else {
            strSql = "insert into student values (" + "‘" + strId + "‘," + "‘"
                    + strName + "‘)";
            if (myDataBase == null) {
                myDataBase = new MyDataBase(this);
            }

            if (myDataBase.ExecSql(strSql)) {
                Toast.makeText(getApplicationContext(), "插入数据成功!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "插入数据失败!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 读取数据
    public void ReadData(View v) {
        if (myDataBase == null) {
            Toast.makeText(getApplicationContext(), "数据库不存在!", Toast.LENGTH_SHORT).show();
        } else {
            SQLiteDatabase db = myDataBase.getReadableDatabase();
            strSql = "select * from student";
            Cursor cursor = db.rawQuery(strSql, null);
            StringBuffer sb = new StringBuffer();
            while (cursor.moveToNext()) {
                Student s = new Student(cursor.getString(0),
                        cursor.getString(1));
                sb.append("学号:" + s.getID() + "     姓名:" + s.getName() + "\n");
            }
            studentList.setText(sb);
        }
    }(注释区的代码是供按钮使用的因为我把按钮都删掉了所以这一段被我注释掉了,如果想添加按钮的话只需要在布局文件里添加按钮然后在这里吧注释符号去掉去壳)*/

    // 菜单被选中
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        int id = item.getItemId();
        if (id == R.id.CreateDataBase) {
            // 创建数据库
            if (myDataBase == null) {
                myDataBase = new MyDataBase(this);
                Toast.makeText(getApplicationContext(), "创建数据库成功!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "数据库已存在!", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.CreateTable) {
            // 创建表
            strSql = "Create table student(" + "ID nvarchar(20) not null,"
                    + "Name nvarchar(40) not null," + "primary key(ID)" + " )";
            if (myDataBase == null) {
                myDataBase = new MyDataBase(this);
            }
            if (myDataBase.ExecSql(strSql)) {
                Toast.makeText(getApplicationContext(), "创建表成功!",Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "创建表失败!", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.DropTable) {
            // 删除表
            strSql = "Drop table student";
            if (myDataBase == null) {
                myDataBase = new MyDataBase(this);
            }
            if (myDataBase.ExecSql(strSql)) {
                Toast.makeText(getApplicationContext(), "删除表成功!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "删除表失败!", Toast.LENGTH_SHORT).show();
            }
        } else if (id == R.id.InsertData) {
            // 插入数据
            String strId = ID.getText().toString();
            String strName = Name.getText().toString();

            if (strId.equals("") || strName.equals("")) {
                Toast.makeText(getApplicationContext(), "学号或姓名不能为空!", Toast.LENGTH_SHORT).show();
            } else {
                strSql = "insert into student values (" + "‘" + strId + "‘,"
                        + "‘" + strName + "‘)";
                if (myDataBase == null) {
                    myDataBase = new MyDataBase(this);
                }

                if (myDataBase.ExecSql(strSql)) {
                    Toast.makeText(getApplicationContext(), "插入数据成功!", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    Toast.makeText(getApplicationContext(), "插入数据失败!", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        } else if (id == R.id.ReadData) {
            // 读取数据
            if (myDataBase == null) {
                Toast.makeText(getApplicationContext(), "数据库不存在!", Toast.LENGTH_SHORT).show();
            } else {
                SQLiteDatabase db = myDataBase.getReadableDatabase();
                strSql = "select * from student";
                Cursor cursor = db.rawQuery(strSql, null);
                StringBuffer sb = new StringBuffer();
                while (cursor.moveToNext()) {
                    Student s = new Student(cursor.getString(0),
                            cursor.getString(1));
                    sb.append( " 姓名:" + s.getName() + "手机号:" + s.getID() +"\n");

                }
                studentList.setText(sb);
            }
        }

        return super.onOptionsItemSelected(item);
    }

    // 显示右上角三个点菜单
    private void makeActionOverflowMenuShown() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}

 

MyDataBase.java

package com.zrdm.sqlitecrud;

import java.util.concurrent.ExecutionException;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDataBase extends SQLiteOpenHelper{

    //变量*********************************************/
    private static String strDataBaseName = "Student.db";
    private static int intVersion = 1;
    private SQLiteDatabase db = null;
    
    //函数********************************************/
    public MyDataBase(Context context){
        super(context, strDataBaseName, null, intVersion);
        db = getWritableDatabase();
    }
    //构造
    public MyDataBase(Context context, String name, CursorFactory factory,
            int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
        // TODO Auto-generated constructor stub
    }

    //构造
    public MyDataBase(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    //执行SQL语句,建议语句类型 create 、delete 、 update 、insert
    public boolean ExecSql(String strSql){
        try{
            db.execSQL(strSql);
            return true;
        }catch(Exception e){
            return false;
        }        
    }    
    
    //创建
    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub
        
    }

    //版本升级
    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub
        
    }
    
}

 

Student.java

package com.zrdm.sqlitecrud;

import java.util.concurrent.ExecutionException;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDataBase extends SQLiteOpenHelper{

    //变量*********************************************/
    private static String strDataBaseName = "Student.db";
    private static int intVersion = 1;
    private SQLiteDatabase db = null;
    
    //函数********************************************/
    public MyDataBase(Context context){
        super(context, strDataBaseName, null, intVersion);
        db = getWritableDatabase();
    }
    //构造
    public MyDataBase(Context context, String name, CursorFactory factory,
            int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
        // TODO Auto-generated constructor stub
    }

    //构造
    public MyDataBase(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    //执行SQL语句,建议语句类型 create 、delete 、 update 、insert
    public boolean ExecSql(String strSql){
        try{
            db.execSQL(strSql);
            return true;
        }catch(Exception e){
            return false;
        }        
    }    
    
    //创建
    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub
        
    }

    //版本升级
    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub
        
    }
    
}

 

点击创建数据库->创建表->插入数据。如果创建表的时候失败就点击删除表然后点击创建表就可以.

技术分享

 

插入数据成功:

技术分享

读取数据成功:

技术分享

SQLlite实现增删查改

标签:

原文地址:http://www.cnblogs.com/laozhanghahaha/p/5537258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!