如何从sqllite表中获取数据

时间:2017-04-15 09:24:24

标签: java android database sqlite

您好,我正在编写需要使用数据库的应用程序,而且我遇到了麻烦。我似乎无法从数据库中获取信息。我有以下代码:

合同类:

public class SettingsContract {
    private SettingsContract() {

    }

    public final class SettingsEntry implements BaseColumns {
        public static final String TABLE_NAME = "Settings";
        public static final String COLUMN_NAME_LAST_REFRESH_DT = "LastRefreshDt";
    }
}

DbHelper课程:

public class SettingsDbHelper extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Database.db";

    private static final String SQL_CREATE_ENTRIES =
        "CREATE TABLE IF NOT EXISTS" + SettingsContract.SettingsEntry.TABLE_NAME + " (" +
                SettingsContract.SettingsEntry._ID + " INTEGER PRIMARY KEY," +
                SettingsContract.SettingsEntry.COLUMN_NAME_LAST_REFRESH_DT + " DATE,";

    private static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + SettingsContract.SettingsEntry.TABLE_NAME;

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }

}

我在哪里使用这段代码:

private SettingsDbHelper dbHelper;

    public SettingsDataSource(Context context) {
        this.dbHelper = new SettingsDbHelper(context);
    }

    public Setting getSettings() {
        SQLiteDatabase db = this.dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT " + 
SettingsContract.SettingsEntry.COLUMN_NAME_LAST_REFRESH_DT + " FROM " 
+ SettingsContract.SettingsEntry.TABLE_NAME, null);
...

现在,当我调用rawQuery时,这就是我在日志中的内容:

04-15 12:18:14.026 2698-2698/com.busridercluj E/SQLiteLog: 
(1) no such table: Settings

我在这里缺少什么?为什么表格没有按原样创建?

2 个答案:

答案 0 :(得分:1)

您的创建表查询错误,因此未创建表。

private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE IF NOT EXISTS " + SettingsContract.SettingsEntry.TABLE_NAME + " (" +
                    SettingsContract.SettingsEntry._ID + " INTEGER PRIMARY KEY," + SettingsContract.SettingsEntry.COLUMN_NAME_LAST_REFRESH_DT + " DATE);";



@Override
    public void onCreate(SQLiteDatabase db) {
      Log.d("CreateDB", "Create table sql query: " + SQL_CREATE_ENTRIES);
      db.execSQL(SQL_CREATE_ENTRIES);
    }

日志输出应为:CREATE TABLE IF NOT EXISTS Settings (_id INTEGER PRIMARY KEY, LastRefreshDt DATE);

答案 1 :(得分:-1)

这可能对你有帮助......

MainActivity.class

public class MainActivity extends Activity {

DatabaseClass dbclass;
EditText et1,et2,et3;
Button b1,b2;

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

    et1 = (EditText) findViewById(R.id.editText1);
    et2 = (EditText) findViewById(R.id.editText2);
    et3 = (EditText) findViewById(R.id.editText3);
    b1 = (Button) findViewById(R.id.button1);
    b2 = (Button) findViewById(R.id.button2);
    dbclass = new DatabaseClass(this);
    onInsert();
    onShow();

}

public void onInsert(){
    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
                          boolean isInserted = dbclass.InsertData(et1.getText().toString(), 
                                  et2.getText().toString(), 
                                  et3.getText().toString());

                          if(isInserted ==true){
                              Toast.makeText(getApplicationContext(), "data inserted", Toast.LENGTH_LONG).show();
                          }else
                              Toast.makeText(getApplicationContext(), "data not inserted", Toast.LENGTH_LONG).show();

        }
    });
}

public void onShow(){
    b2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent in = new Intent(getApplicationContext(),ListActivity.class);
            startActivity(in);
            }
    });
}

}

助手类

public class DatabaseClass extends SQLiteOpenHelper{

public static final String DATABASE_NAME = "Student.db";
public static final String TABLE_NAME = "StudentData";
public static final String ID= "id";
public static final String NAME = "name";
public static final String SURNAME = "surname";
public static final String MARKS = "marks";

public DatabaseClass(Context context) {
    super(context, TABLE_NAME, null, 1);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)"); 

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
    onCreate(db);
}

public boolean InsertData(String name,String surname,String marks){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put("NAME", name);
    cv.put("SURNAME", surname);
    cv.put("MARKS", marks);
    long result = db.insert(TABLE_NAME, null, cv);
    if(result==-1){
        return false;
    }
    return true;
}

public Cursor getAllData(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("SELECT * FROM TABLE NAME", null);
    return res;
}

}

ListActivity.class

public class ListActivity extends Activity {

ListView l;
DatabaseClass dba;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.thelist);
    dba = new DatabaseClass(this);

    l = (ListView) findViewById(R.id.listView1);
    ViewAll();



}

public void ViewAll(){
    Cursor res = dba.getAllData();
    if(res.getCount()==0){
        Toast.makeText(this, "no data found", Toast.LENGTH_LONG).show();
        return;
    }

    /*StringBuffer buffer = new StringBuffer();
    while(res.moveToNext()){
        buffer.append("ID"+res.getString(0)+"\n");
        buffer.append("NAME"+res.getString(1)+"\n");
        buffer.append("SURNAME"+res.getString(2)+"\n");
        buffer.append("PRICE"+res.getString(3)+"\n");
    }*/
    //showmessage("DATA",buffer.toString());        
    ArrayAdapter<String> adap = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,);
    l.setAdapter(adap);
}

}

Adapter.class

public class MyAdapter extends ArrayAdapter<String> {

private final Context context;
private final String[] values;

public MyAdapter(Context context,String[] values) {
    super(context, R.layout.thelist, values);
    this.context = context;
    this.values = values;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.listitems, parent,false);
    return super.getView(position, convertView, parent);

    TextView tv1 = (TextView) row.findViewById(R.id.textname);
    TextView tv2 = (TextView) row.findViewById(R.id.textsurname);
    TextView tv3 = (TextView) row.findViewById(R.id.textmarks);
}

}