本帖最后由 情祭 于 2013-12-21 17:14 编辑
package cn.lzf;
import android.app.Activity;
import android.database.Cursor;
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;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText city,number;
TextView show;
Button add,delete,chaxun;
SQLiteDatabase sld;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
city=(EditText)findViewById(R.id.city);
number=(EditText)findViewById(R.id.number);
show=(TextView)findViewById(R.id.show);
add=(Button)findViewById(R.id.add);
delete=(Button)findViewById(R.id.delete);
chaxun=(Button)findViewById(R.id.chaxun);
//创建数据库
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sld=SQLiteDatabase.openDatabase("/data/data/cn.lzf/mydb1",
null,SQLiteDatabase.OPEN_READONLY|SQLiteDatabase.CREATE_IF_NECESSARY);
String sq1="create table if not exists student(city varchar(10),number interger)";
sld.execSQL(sq1);
String citys=city.getText().toString();
String numbers=number.getText().toString();
String sq2="insert into student values(?,?)";
sld.execSQL(sq2,new String[]{citys,numbers});
Toast.makeText(MainActivity.this,"增加成功",100).show();
}
});
//删除记录
delete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String sql="delete from student";
sld.execSQL(sql);
Toast.makeText( MainActivity.this,"记录全部被删除",100).show();
}
});
//查询记录
chaxun.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try{
String sq3="select * from student";
Cursor cur=sld.rawQuery(sq3,null);//Cursor主要用于存放查询的记录,是结果集游标,
//用于对结果集进行随机访问。
show.append("城市名"+"\t"+"区号"+"\n");
while(cur.moveToNext()){//moveToNext()方法可以将游标从当前记录移动到下一条记录,
//如果已经移过了结果集的最后一条记录,返回false,否则返回true.
String scity=cur.getString(0);
int snumber=cur.getInt(1);
show.append(scity+"\t"+snumber+"\t");
}
cur.close();
}
catch(Exception e){
Toast.makeText( MainActivity.this, "数据库错误:"+e.toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
http://bbs.itheima.com/forum.php?mod=attachment&aid=MzE4OTF8MGYyNzZlYjI0M2FiYWZmYzBiNjM4ZDJhMWYyOGU5NWZ8MTczMTI3MDk4Mg%3D%3D&request=yes&_f=.png
http://bbs.itheima.com/forum.php?mod=attachment&aid=MzE4OTJ8NDUzODgzZjNmZjBkMmUwMzNiMmRmM2E0ZjBiZGIzNTd8MTczMTI3MDk4Mg%3D%3D&request=yes&_f=.png
|
|