Android数据库连接和操作

时间:2014-06-29 11:58:01

标签: android database

我正在尝试在android数据库中添加数据然后尝试从列表中检索数据但是我收到错误。我为MainActivity创建了三个java文件,一个用于数据库连接,另一个用于信息

这是MainActivity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DatabaseHandler db=new DatabaseHandler(this);

    /*inserting dat*/
    Log.d("Insert", "Element inserting");
    db.addcontacts(new Contact("Ravi", "9100000000"));        
    db.addcontacts(new Contact("Srinivas", "9199999999"));
    db.addcontacts(new Contact("Tommy", "9522222222"));
    db.addcontacts(new Contact("Karthik", "9533333333"));

 // Reading all contacts
    Log.d("Reading: ", "Reading all contacts.."); 
    ArrayList<Contact> contacts = db.getallcontact();       

    for (Contact cn : contacts) {
        String log = "Id: "+cn.getId()+" ,Name: " + cn.getName() + " ,Phone: " +     
       cn.getPhonenumber();
            // Writing Contacts to log
    Log.d("Name: ", log);
    }
}

@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;
}

    }

这是Contact.java

 public class Contact {

    private int _ID;
    private String _name;
    private String _phone_number;
    public Contact(){
    }

    public Contact(int id,String Name, String Phone_Number){
        _ID=id;
        _name=Name;
        _phone_number=Phone_Number;
    }

    public Contact(String Phone_Number,String Name){
        _name=Name;
        _phone_number=Phone_Number;
    }


    public int getId(){
        return _ID;
    }
    public String getName(){
        return _name;
    }

    public String getPhonenumber(){
        return _phone_number;
    }
    public void setName(String name){
        _name=name;
    }
    public void setPhonenumber(String phone){
        _phone_number=phone;
    }

    public void setId(int id) {
        // TODO Auto-generated method stub
        _ID=id;
    }
        }

这是databasehandler.java

public class DatabaseHandler extends SQLiteOpenHelper {

private  static int version=1;
private static final String DATABASE_NAME="contactManager";
private static String KEY_ID="id";
private static String KEY_NAME="name";
private static String KEY_PH_NO="phone_number";
private static String TABLE_CONTACTS="contacts";
public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, version);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub
    String TABLE_CREATE="create"+TABLE_CONTACTS+"("+KEY_ID+"integer primary key   
    autoincrement,"+
    KEY_NAME+"text,"+KEY_PH_NO+"text;)";
    arg0.execSQL(TABLE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    // TODO Auto-generated method stub
    arg0.execSQL("drop TABLE IF EXITS"+TABLE_CONTACTS);
    onCreate(arg0);
}
public void addcontacts(Contact contact){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues values=new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhonenumber());
    db.insert(TABLE_CONTACTS, null, values);
    db.close();

}
public Contact getcontact(int id){
    SQLiteDatabase db=this.getReadableDatabase();
    Cursor cursor=db.query(TABLE_CONTACTS,new  String[]{KEY_ID,  
        KEY_NAME,KEY_PH_NO},KEY_ID+"?",  new String[] { String.valueOf(id) },  
        null,null, null);
    if(cursor!=null){
        cursor.moveToFirst();
    }
    Contact contact=new  

Contact(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2));
return contact;
}
    public ArrayList<Contact> getallcontact(){
ArrayList<Contact> contactlist=new ArrayList<Contact>();
SQLiteDatabase db=this.getReadableDatabase();
 String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
Cursor cursor=db.rawQuery(selectQuery, null);
if(cursor.moveToFirst())
{
    do{
        Contact contact=new Contact();
        contact.setId(Integer.parseInt (cursor.getString(0)));
        contact.setName(cursor.getString(1));
        contact.setPhonenumber(cursor.getString(2));
        contactlist.add(contact);
    }while(cursor.moveToNext());
}
return contactlist;

   }
    }

这里是logcat

   06-29 07:38:51.640: D/Insert(1057): Element inserting
    06-29 07:38:52.000: E/SQLiteLog(1057): (1) near "createcontacts": syntax error
    06-29 07:38:52.010: D/AndroidRuntime(1057): Shutting down VM
    06-29 07:38:52.010: W/dalvikvm(1057): threadid=1: thread exiting with uncaught    
    exception (group=0xb4a6bb90)
    06-29 07:38:52.080: E/AndroidRuntime(1057): FATAL EXCEPTION: main
    06-29 07:38:52.080: E/AndroidRuntime(1057): Process: com.example.datbase, PID: 1057
    06-29 07:38:52.080: E/AndroidRuntime(1057): java.lang.RuntimeException: Unable to start   
    activity ComponentInfo{com.example.datbase/com.example.datbase.MainActivity}:  
    android.database.sqlite.SQLiteException: near "createcontacts": syntax error (code 1):  
    , while compiling: createcontacts(idinteger primary key 
    autoincrement,nametext,phone_numbertext;)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at    
    android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at   
    android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at  
    android.app.ActivityThread.access$700(ActivityThread.java:135)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at     
    android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at   
    android.os.Handler.dispatchMessage(Handler.java:102)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at   
    android.os.Looper.loop(Looper.java:137)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at  
    android.app.ActivityThread.main(ActivityThread.java:4998)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at   
    java.lang.reflect.Method.invokeNative(Native Method)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at   
    java.lang.reflect.Method.invoke(Method.java:515)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at   
    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at  
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
    06-29 07:38:52.080: E/AndroidRuntime(1057):     at    
    dalvik.system.NativeStart.main(Native Method)
    06-29 07:38:52.080: E/AndroidRuntime(1057): Caused by:   
    android.database.sqlite.SQLiteException: near "createcontacts": syntax error (code 1):   
    , while compiling: createcontacts(idinteger primary key  
    autoincrement,nametext,phone_numbertext;)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at   
   android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at android.database.sqlite.SQLiteProgram. 
   <init>(SQLiteProgram.java:58)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at android.database.sqlite.SQLiteStatement. 
   <init>(SQLiteStatement.java:31)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1672)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1603)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   com.example.datbase.DatabaseHandler.onCreate(DatabaseHandler.java:31)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at   
   android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   com.example.datbase.DatabaseHandler.addcontacts(DatabaseHandler.java:41)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   com.example.datbase.MainActivity.onCreate(MainActivity.java:20) 
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at   
   android.app.Activity.performCreate(Activity.java:5243)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  at  
   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
   06-29 07:38:52.080: E/AndroidRuntime(1057):  ... 11 more
   06-29 07:43:52.690: I/Process(1057): Sending signal. PID: 1057 SIG: 9

3 个答案:

答案 0 :(得分:1)

这是Space之后的Key_ID问题。你需要提供适当的空间

String TABLE_CREATE="create "+TABLE_CONTACTS+" ("+KEY_ID+" integer primary key   
    autoincrement, "+
    KEY_NAME+" text, "+KEY_PH_NO+" text;)";

此ID应该是_id,因为android在许多操作中使用此约定

private static String KEY_ID="_id";

答案 1 :(得分:1)

尝试这样创建table.code如下:

String TABLE_CREATE = "CREATE TABLE "+ TABLE_CONTACTS + " (" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+KEY_NAME+ " TEXT," +KEY_PH_NO+ " TEXT"  + ")";

我希望这能解决你的问题。

答案 2 :(得分:0)

KEY_ID和&#34之间没有空格;整数主键自动增量&#34;所以添加一个空格

private static String KEY_ID="id ";" integer primary key autoincrement