SQLlite实现增删查改
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实现增删查改的更多相关文章
- [置顶] cocos2dx sqllite 增删查改等操作
首先导入文件shell.c sqllite3.c sqlite3.h sqlite3etx.h文件(注意在生成安卓项目是 不要将shell.c写进android.mk文件中,写进去在cywin中生成会 ...
- 6.在MVC中使用泛型仓储模式和依赖注入实现增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- 3.EF 6.0 Code-First实现增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-entity-framework-5-0-code- ...
- 4.在MVC中使用仓储模式进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-using-the-repository-pattern-in-mvc/ 系列目录: ...
- 5.在MVC中使用泛型仓储模式和工作单元来进行增删查改
原文链接:http://www.c-sharpcorner.com/UploadFile/3d39b4/crud-operations-using-the-generic-repository-pat ...
- jdbc的实例应用:增删查改实现
//在jdbc中进行增删查改 //查看所有 public static void findAll() { String url = "jdbc:mysql://localhost:3306/ ...
- 用javascript实现html元素的增删查改[xyytit]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- hibernate基础增删查改简单实例
hibernate 基础理论知识网上很多,可以百度和google.这里不做多的介绍,以一个User表来开展例子 建一个web-project 我这里用了junit单元测试环境来进行增删查改的测试,别的 ...
- Entity FrameWork 增删查改的本质
之前的文章里面已经说了,EF的增删查改.那时候的修改,删除,只能是先查询出来要修改的数据,再修改,删除...现在来一个改进版的,增删查改. 1.Add static void Add() { //1. ...
随机推荐
- HDFS 01 - HDFS是什么?它的适用场景有哪些?它的架构是什么?
目录 1.HDFS 是什么 1.1 简单介绍 1.2 发展历史 2.HDFS 应用场景 2.1 适合的应用场景 2.2 不适合的应用场景 3.HDFS 的架构 4.NameNode 和 DataNod ...
- 扒几个 3D 模型备用
前言 在上一篇中,我展示了 OpenGL 开发的基本过程,算是向 3D 世界迈出的一小步吧.对于简单的 3D 物体,比如立方体.球体.圆环等等,我们只需要简单的计算就可以得到他们的顶点的坐标.但是仅仅 ...
- 设置mysql的字符集永远为UTF-8
1.在虚拟机/usr路径下创建一个文件命名为:mysql.cnf cd /usr touch mysql.cnf 2.在该文件中使用vim命令插入配置文本 vim mysql.cnf 按i键进入编辑模 ...
- Java中出现Unhandled exception的原因
说明某个方法在方法声明上已经声明了会抛异常,那么在调用这个方法的时候,就必须做异常处理,处理的方式有2种,要么try-catch这个异常,要么继续往上一层抛出这个异常,这是java语法要求的,必须这么 ...
- 解决bs4在python中出现“ImportError: cannot import name ‘HTMLParseError‘”错误
在使用BeautifulSoup4时候出现了ImportError: cannot import name 'HTMLParseError'的错误. 根本原因是BeautifulSoup在4.4.0以 ...
- Spring Boot集成Springfox Swagger3和简单应用
摘要:Springfox Swagger可以动态生成 API 接口供前后端进行交互和在线调试接口,Spring Boot 框架是目前非常流行的微服务框架,所以,在Spring Boot 项目中集成Sp ...
- es6 快速入门 —— 函数
其他章节请看: es6 快速入门 系列 函数 函数是所有编程语言的重要组成部分,es6之前函数语法一直没什么变化,遗留了许多问题,javaScript开发者多年来不断抱怨,es6终于决定大力度更新函数 ...
- Spring Boot 老启动失败,这次再也不怕了!
Spring Boot 项目是不是经常失败,显示一大堆的错误信息,如端口重复绑定时会打印以下异常: *************************** APPLICATION FAILED TO ...
- HDOJ-1074(动态规划+状态压缩)
Doing Homework HDOJ-1074 1.本题主要用的是状态压缩的方法,将每种状态用二进制压缩表示 2.状态转移方程:dp[i|(1<<j)]=min(dp[i|(1<& ...
- 通达OA 任意文件上传-2013/2015版本
参考 http://wiki.0-sec.org/0day/%E9%80%9A%E8%BE%BEoa/11.html 影响版本 2013版本 2015版本 漏洞文件 general/vmeet/wbU ...