数据库SQLite的增删改查简单的实现

*********************SQLite是比较小而功能比较全的关系型数据库,下面介绍一下SQLite数据库的使用方法,及增删改查操作。**************

***********代码如下:

                             **********************MaActivity.class*******************

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText ename;
	private EditText ecolor;
	private EditText eprice;
	private Button look;
	private Button add;
	private MySQLite mySQLite;
	private CarDao dao;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ename = (EditText) findViewById(R.id.ename);
		ecolor = (EditText) findViewById(R.id.ecolor);
		eprice = (EditText) findViewById(R.id.eprice);
		look = (Button) findViewById(R.id.look);
		add = (Button) findViewById(R.id.add);

		mySQLite = new MySQLite(this);
		dao = new CarDao(this);
		
		add.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String name = ename.getText().toString().trim();
				String color = ecolor.getText().toString().trim();
				String price = eprice.getText().toString().trim();
				if (TextUtils.isEmpty(name) && TextUtils.isEmpty(color)
						&& TextUtils.isEmpty(price)) {
					Toast.makeText(MainActivity.this, "不能为空", 0).show();
				}
				long addDate = dao.addDate(name, color, price);
				if(addDate>0){
					Toast.makeText(MainActivity.this, "添加成功", 0).show();
				}
			}
		});
		look.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, ShowActivity.class);
				startActivity(intent);
				finish();
			}
		});

	}
}


                                      **********************MySQLite.class*******************

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

public class MySQLite extends SQLiteOpenHelper {

	public MySQLite(Context context) {
		super(context, "h.db", null, 1);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("create table car(_id integer primary key autoincrement,name varchar(0),color varchar(0),price varchar(0))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}

                                            **********************Car.class(Bean)*******************

public class Car {
	private int _id;
	private String name;
	private String color;
	private String price;
	public int get_id() {
		return _id;
	}
	public void set_id(int _id) {
		this._id = _id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getColor() {
		return color;
	}
	public void setColor(String color) {
		this.color = color;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}
	public Car(int _id, String name, String color, String price) {
		super();
		this._id = _id;
		this.name = name;
		this.color = color;
		this.price = price;
	}
	public Car() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Car(String name, String color, String price) {
		super();
		this.name = name;
		this.color = color;
		this.price = price;
	}
	

}


                                                    **********************CarDao.class*******************

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class CarDao {
	private MySQLite mySQLite;
	private ArrayList<Car> list;

	public CarDao(Context con) {
		mySQLite = new MySQLite(con);
	}

	// 添加
	public long addDate(String name, String color, String price) {

		SQLiteDatabase db = mySQLite.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("name", name);
		values.put("color", color);
		values.put("price", price);

		long insert = db.insert("car", null, values);
		db.close();
		return insert;
	}

	// 查询
	@SuppressLint("NewApi")
	public ArrayList<Car> query() {
		list = new ArrayList<Car>();
		SQLiteDatabase db = mySQLite.getWritableDatabase();
		Cursor query = db.query(false, "car", null, null, null, null, null,
				null, null, null);
		while (query.moveToNext()) {
			int _id = query.getInt(query.getColumnIndex("_id"));
			String name = query.getString(query.getColumnIndex("name"));
			String color = query.getString(query.getColumnIndex("color"));
			String price = query.getString(query.getColumnIndex("price"));

			list.add(new Car(_id, name, color, price));
		}
		db.close();
		return list;

	}

	// 模糊查询
	@SuppressLint("NewApi")
	public ArrayList<Car> query(String ename) {
		list = new ArrayList<Car>();
		SQLiteDatabase db = mySQLite.getWritableDatabase();
		Cursor query = db.query("car", null, "name like ?", new String[]{"%"+ename+"%"} , null, null, null);
		while (query.moveToNext()) {
			int _id = query.getInt(query.getColumnIndex("_id"));
			String name = query.getString(query.getColumnIndex("name"));
			String color = query.getString(query.getColumnIndex("color"));
			String price = query.getString(query.getColumnIndex("price"));

			list.add(new Car(_id, name, color, price));
		}
		db.close();
		return list;

	}

	// 删除
	public int delete(int _id) {

		SQLiteDatabase db = mySQLite.getWritableDatabase();
		int d = db.delete("car", "_id=?", new String[] { _id + "" });

		db.close();
		return d;

	}

	// 修改
	public int update(int _id, String name, String color, String price) {
		SQLiteDatabase db = mySQLite.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("name", name);
		values.put("color", color);
		values.put("price", price);
		values.put("_id", _id);

		int u = db.update("car", values, "_id=?", new String[] { _id + "" });
		db.close();
		return u;

	}

}


                                                       **********************ShowActivity.class*******************

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ShowActivity extends Activity {

	private ListView listView;
	private MySQLite mySQLite;
	private CarDao dao;
	private BaseAdapter adapter;
	private ArrayList<Car> list;
	private EditText sname;
	private Button ss;

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_show);
		listView = (ListView) findViewById(R.id.listView);
		sname = (EditText) findViewById(R.id.sname);
		ss = (Button) findViewById(R.id.ss);

		mySQLite = new MySQLite(this);
		dao = new CarDao(this);
		list=new ArrayList<Car>();
		list = dao.query();

		SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
				R.layout.show, null, new String[] { "name", "color", "price" },
				new int[] { R.id.name, R.id.color, R.id.price });

		//搜索
		ss.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(ShowActivity.this, "ddd", 0).show();
				adapter.notifyDataSetChanged();
				String name = sname.getText().toString().trim();
				
				if(TextUtils.isEmpty(name)){
					list=dao.query();
				}
				list=dao.query(name);
			}
		});
		//长按删除
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			private Builder builder;

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					final int position, long id) {
				// TODO Auto-generated method stub
				
				builder = new Builder(ShowActivity.this);
				builder.setTitle("温馨提示").setMessage("确定要干掉它?").setNegativeButton("NO", null).setPositiveButton("YES", new OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						int delete = dao.delete(list.get(position).get_id());
						if(delete>0){
							Toast.makeText(ShowActivity.this, "删除成功", 0).show();
						}
						list.remove(position);
						adapter.notifyDataSetChanged();
					}
				});
				builder.show();
				return false;
			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				String name = list.get(position).getName();
				String color = list.get(position).getColor();
				String price = list.get(position).getPrice();
				int _id = list.get(position).get_id();
				
				Intent intent = new Intent(ShowActivity.this, UpdateActivity.class);
				intent.putExtra("name", name);
				intent.putExtra("color", color);
				intent.putExtra("price", price);
				intent.putExtra("_id", _id);
				startActivity(intent);
				finish();
			}
		});
		
		//适配器
		listView.setAdapter(adapter = new BaseAdapter() {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				// TODO Auto-generated method stub
				View view = View
						.inflate(ShowActivity.this, R.layout.show, null);
				TextView name = (TextView) view.findViewById(R.id.name);
				TextView color = (TextView) view.findViewById(R.id.color);
				TextView price = (TextView) view.findViewById(R.id.price);
				name.setText(list.get(position).getName());
				color.setText(list.get(position).getColor());
				price.setText(list.get(position).getPrice());
				return view;
			}

			@Override
			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return 0;
			}

			@Override
			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return null;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return list.size();
			}
		});
		//adapter.notifyDataSetChanged();
	}
}

                                              **********************UpdateActivity.class*******************

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class UpdateActivity extends Activity {

	private EditText ename;
	private EditText ecolor;
	private EditText eprice;
	private Button bao;
	private Button fan;
	private MySQLite mySQLite;
	private CarDao dao;
	private int _id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_update);

		ename = (EditText) findViewById(R.id.ename);
		ecolor = (EditText) findViewById(R.id.ecolor);
		eprice = (EditText) findViewById(R.id.eprice);
		bao = (Button) findViewById(R.id.bao);
		fan = (Button) findViewById(R.id.fan);

		Intent intent = getIntent();
		String name = intent.getStringExtra("name");
		String color = intent.getStringExtra("color");
		String price = intent.getStringExtra("price");
		_id = intent.getIntExtra("_id",0);
		ename.setText(name);
		ecolor.setText(color);
		eprice.setText(price);
		mySQLite = new MySQLite(this);
		dao = new CarDao(this);
		
		bao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String name = ename.getText().toString().trim();
				String color = ecolor.getText().toString().trim();
				String price = eprice.getText().toString().trim();
				if (TextUtils.isEmpty(name) && TextUtils.isEmpty(color)
						&& TextUtils.isEmpty(price)) {
					Toast.makeText(UpdateActivity.this, "不能为空", 0).show();
				}
				int u = dao.update(_id, name, color, price);
				if(u>0){
					Toast.makeText(UpdateActivity.this, "保存成功", 0).show();
				}
				
			}
		});
		fan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(UpdateActivity.this, ShowActivity.class);
				startActivity(intent);
				finish();
			}
		});

	}

}

       *************************以下是所有布局*******

                                             *************** activity_main.xml*********************

<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"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp"
        android:text="添加汽车" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textView1"
        android:layout_marginTop="43dp"
        android:text="名称:" />

    <EditText
        android:id="@+id/ename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/textView2"
        android:layout_marginLeft="17dp"
        android:layout_toRightOf="@id/textView2"
        android:ems="10" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textView2"
        android:layout_marginTop="52dp"
        android:text="颜色:" />

    <EditText
        android:id="@+id/ecolor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/textView3"
        android:layout_alignLeft="@id/ename"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="价格:" />

    <EditText
        android:id="@+id/eprice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/textView4"
        android:layout_alignLeft="@id/ecolor"
        android:ems="10" />

    <Button
        android:id="@+id/add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/eprice"
        android:layout_below="@id/eprice"
        android:layout_marginTop="81dp"
        android:text="添加" />

    <Button
        android:id="@+id/look"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/add"
        android:layout_alignRight="@id/eprice"
        android:layout_marginRight="26dp"
        android:text="查看" />

</RelativeLayout>

                                             *************** activity_show.xml*********************

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <EditText
        android1:id="@+id/sname"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content"
        android1:layout_alignParentLeft="true"
        android1:layout_alignParentTop="true"
        android1:layout_marginTop="32dp"
        android1:ems="10" />

    <Button
        android1:id="@+id/ss"
        android1:layout_width="wrap_content"
        android1:layout_height="wrap_content"
        android1:layout_alignBaseline="@id/sname"
        android1:layout_alignBottom="@id/sname"
        android1:layout_marginLeft="14dp"
        android1:layout_toRightOf="@id/sname"
        android1:text="搜索" />

    <ListView
        android1:id="@+id/listView"
        android1:layout_width="match_parent"
        android1:layout_height="wrap_content"
        android1:layout_alignParentLeft="true"
        android1:layout_below="@id/ss"
        android1:layout_marginTop="18dp" >
    </ListView>

</RelativeLayout>


                                                              *************** activity_update.xml*********************

<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"
    >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="30dp"
        android:text="修改汽车" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textView1"
        android:layout_marginTop="43dp"
        android:text="名称:" />

    <EditText
        android:id="@+id/ename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/textView2"
        android:layout_marginLeft="17dp"
        android:layout_toRightOf="@id/textView2"
        android:ems="10" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textView2"
        android:layout_marginTop="52dp"
        android:text="颜色:" />

    <EditText
        android:id="@+id/ecolor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/textView3"
        android:layout_alignLeft="@id/ename"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:text="价格:" />

    <EditText
        android:id="@+id/eprice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/textView4"
        android:layout_alignLeft="@id/ecolor"
        android:ems="10" />

    <Button
        android:id="@+id/bao"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/eprice"
        android:layout_below="@id/eprice"
        android:layout_marginTop="81dp"
        android:text="保存" />

    <Button
        android:id="@+id/fan"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/bao"
        android:layout_alignRight="@id/eprice"
        android:layout_marginRight="26dp"
        android:text="返回" />

</RelativeLayout>


                                                             *************** show.xml*********************

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/color"
        android:layout_marginLeft="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/price"
        android:layout_marginLeft="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>


                                                               *****OK*****

阅读更多
换一批

没有更多推荐了,返回首页