做任何开发都会用的数据库,Android也一样,Android一般都要用的两个数据库本地数据库和远程数据库,本地数据库就是sqlite,远程数据库的话,我一般用的是mysql,这次先了解下本地数据库sqlite,一般数据库类型为varchar(20) 如果你输入个大于20位的数据时,会报错,不能插入吧,但是sqlite里就不一样了,他就可以,这是sqlite的特色之一吧应该是。下来就看看sqlite的 crud:
MainActivity
package com.example.sqlite; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView t; DBOpenHelter dbopenhelper=new DBOpenHelter(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
PersonService
package com.example.sqlite; import com.example.bean.Person; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class PersonService { private DBOpenHelter dbOpenHelper; public PersonService(Context context){ this.dbOpenHelper=new DBOpenHelter(context); } public void save(Person person){ SQLiteDatabase db=dbOpenHelper.getWritableDatabase(); StringBuilder sql=new StringBuilder(128); //这个没用 sql.append("insert "); //这个没用 db.execSQL("insert into person(name,phone) values(?,?)",new Object[]{person.getName(),person.getPhone()}); db.close(); } public Person find(Integer id){ Person person=new Person(); SQLiteDatabase db=dbOpenHelper.getReadableDatabase(); Cursor cursor=db.rawQuery("select * from testpersion wehre name=?",new String[]{id.toString()}); while(cursor.moveToNext()){ int personid=cursor.getInt(cursor.getColumnIndex("id")); } return person; } }
DBOpenHelter
package com.example.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DBOpenHelter extends SQLiteOpenHelper{
public DBOpenHelter(Context context) {
super(context, "itcast.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE testpersion(persionid integer primary key autoincrement,name varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("ALTER TABLE testpersion ADD phone VARCHAR(12) NULL");
}
}