如何在Android中编写SQLite execSQL函数?

时间:2013-01-10 13:00:48

标签: java android sqlite

我正在开发一个应用程序,我需要检索一些数据并存储在SQLite数据库中。我正在使用SQLiteOpenHelper。这里databaseHandler.addDetails(obj);呈现错误消息。任何帮助,将不胜感激。这是我的代码。

Register.java

public class Register extends Activity{

//  variables for all text data.
    String FIRSTNAME = null;
    String LASTNAME = null;
    String USERNAME = null;
    String PASSWORD = null;
    String CITY= null;

//  variables for individual ID s .
    EditText fnameText = null;
    EditText lnameText = null;
    EditText unameText = null;
    EditText passText = null;
    EditText cityText = null;
    Button redg = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);


        fnameText = (EditText)findViewById(R.id.editText1);
        lnameText = (EditText)findViewById(R.id.editText2);
        unameText = (EditText)findViewById(R.id.editText3);
        passText = (EditText)findViewById(R.id.editText4);
        cityText = (EditText)findViewById(R.id.editText5);
        redg = (Button)findViewById(R.id.button1);

//      button click event
        redg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                System.out.println("On click event of Register Activity..........");
                UserDetailsClass obj = new UserDetailsClass();
                FIRSTNAME = fnameText.getText().toString();
                LASTNAME = lnameText.getText().toString();
                USERNAME = unameText.getText().toString();
                PASSWORD = passText.getText().toString();
                CITY = cityText.getText().toString();

                 obj.setFname(FIRSTNAME);
                 obj.setLname(LASTNAME);
                 obj.setUname(USERNAME);
                 obj.setPass(PASSWORD);
                 obj.setCity(CITY);
                 System.out.println("object set in Register Activity........");
                DatabaseHandler databaseHandler = new DatabaseHandler(getApplicationContext());
                System.out.println("Database handler created ........");
                databaseHandler.addDetails(obj);
            }
        });

    }
}

DatabaseHandler.java

public class DatabaseHandler  extends SQLiteOpenHelper{


    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "UserManager";

    // Contacts table name
    private static final String USER_DETAILS = "userdetails";

    // Contacts Table Columns names
    private static final String KEY_FNAME = "fname";
    private static final String KEY_LNAME = "lname";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_CITY = "city";


    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println(" begin of table creation...");
        String CREATE_USER_TABLE = "CREATE TABLE " + USER_DETAILS + "(" + KEY_FNAME + "TEXT," 
        + KEY_LNAME + "TEXT," + KEY_PASSWORD + "TEXT," + KEY_USERNAME + " TEXT PRIMARY KEY," 
        + KEY_CITY + " TEXT" + ")";
        db.execSQL(CREATE_USER_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + USER_DETAILS);

        // Create tables again
        onCreate(db);
    }


//   REGISTERING USER METHOD 
    void addDetails(UserDetailsClass obj) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_FNAME, obj.getFname());
        values.put(KEY_LNAME, obj.getLname());
        values.put(KEY_USERNAME, obj.getUname());
        values.put(KEY_PASSWORD, obj.getPass());
        values.put(KEY_CITY, obj.getCity());

        // Inserting Row
        db.insert(USER_DETAILS, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact
     UserDetailsClass getDetails(String uname, String pass) {
        SQLiteDatabase db = this.getReadableDatabase();
        System.out.println("I'm in getDetails() of DatabaseHandler .......");
        Cursor cursor = db.query(USER_DETAILS, new String[] { KEY_FNAME,KEY_LNAME,KEY_USERNAME,
                KEY_PASSWORD, KEY_CITY }, KEY_USERNAME + "=? & " + KEY_PASSWORD + "=?",
                new String[] { String.valueOf(uname), String.valueOf(pass) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        UserDetailsClass obj1 = new UserDetailsClass();
        obj1.setFname(cursor.getString(0));
        obj1.setLname(cursor.getString(1));
        obj1.setUname(cursor.getString(2));
        obj1.setPass(cursor.getString(3));
        obj1.setCity(cursor.getString(4));
        // return contact
        return obj1;
    }
}

UserDetailsClass.java

public class UserDetailsClass {
    public String fname = null;
    public String lname = null;
    public String Uname = null;
    public String Pass = null;
    public String city = null;
    public String getFname() {
        return fname;
    }
    public void setFname(String fname) {
        this.fname = fname;
    }
    public String getLname() {
        return lname;
    }
    public void setLname(String lname) {
        this.lname = lname;
    }
    public String getUname() {
        return Uname;
    }
    public void setUname(String uname) {
        Uname = uname;
    }
    public String getPass() {
        return Pass;
    }
    public void setPass(String pass) {
        Pass = pass;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }

}

这里是我的logcat。

01-10 18:08:46.782: E/Database(334): Error inserting username=jmwtp  lname=gjtp  password=ajtp fname=gjm  city=address 
01-10 18:08:46.782: E/Database(334): android.database.sqlite.SQLiteException: table userdetails has no column named lname: , while compiling: INSERT INTO userdetails(username, lname, password, fname, city) VALUES(?, ?, ?, ?, ?);
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:41)
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteDatabase.compileStatement(SQLiteDatabase.java:1149)
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1569)
01-10 18:08:46.782: E/Database(334):    at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1426)
01-10 18:08:46.782: E/Database(334):    at com.bam.testdatabse.DatabaseHandler.addDetails(DatabaseHandler.java:67)
01-10 18:08:46.782: E/Database(334):    at com.bam.testdatabse.Register$1.onClick(Register.java:62)
01-10 18:08:46.782: E/Database(334):    at android.view.View.performClick(View.java:2485)
01-10 18:08:46.782: E/Database(334):    at android.view.View$PerformClick.run(View.java:9080)
01-10 18:08:46.782: E/Database(334):    at android.os.Handler.handleCallback(Handler.java:587)
01-10 18:08:46.782: E/Database(334):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-10 18:08:46.782: E/Database(334):    at android.os.Looper.loop(Looper.java:123)
01-10 18:08:46.782: E/Database(334):    at android.app.ActivityThread.main(ActivityThread.java:3683)
01-10 18:08:46.782: E/Database(334):    at java.lang.reflect.Method.invokeNative(Native Method)
01-10 18:08:46.782: E/Database(334):    at java.lang.reflect.Method.invoke(Method.java:507)
01-10 18:08:46.782: E/Database(334):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-10 18:08:46.782: E/Database(334):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-10 18:08:46.782: E/Database(334):    at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:4)

您的数据库创建中缺少空格:

String CREATE_USER_TABLE = "CREATE TABLE " + USER_DETAILS + "(" + KEY_FNAME + "TEXT," 
        + KEY_LNAME + "TEXT," + KEY_PASSWORD + "TEXT," + KEY_USERNAME + " TEXT PRIMARY KEY," 
        + KEY_CITY + " TEXT" + ")";

更改为:

String CREATE_USER_TABLE = "CREATE TABLE " + USER_DETAILS + "(" + KEY_FNAME + "TEXT," 
        + KEY_LNAME + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_USERNAME + " TEXT PRIMARY KEY," 
        + KEY_CITY + " TEXT" + ")";

答案 1 :(得分:2)

从您的日志中

  

01-10 18:08:46.782:E / Database(334):android.database.sqlite.SQLiteException:table userdetails没有名为lname:的列,在编译时:INSERT INTO userdetails(username,lname,password,fname ,城市)VALUES(?,?,?,?,?);

您没有专栏lname。正如其他人已经指出的那样,您需要在列名和相应类型之间添加空格。

KEY_LNAME + " TEXT, "

getDetails()中,您在where子句中使用&运算符。 AFAIK,这是二进制文件,不是逻辑和操作符。我想,您应该使用and代替

Cursor cursor = db.query(..., KEY_USERNAME + " = ? and " + KEY_PASSWORD + " = ?", ...);

答案 2 :(得分:2)

您需要在create table命令中添加空格。以下是更新的命令。

String CREATE_USER_TABLE = "CREATE TABLE " + USER_DETAILS + "(" + KEY_FNAME + " TEXT, " 
        + KEY_LNAME + " TEXT, " + KEY_PASSWORD + " TEXT, " + KEY_USERNAME + " TEXT PRIMARY KEY, " 
        + KEY_CITY + " TEXT" + ")";

答案 3 :(得分:2)

错误表明您的数据库中没有名为“lname”的列。 尝试在创建表格查询中添加空格KEY_LNAME + "TEXT," => lnameTEXT