首页 \ 问答 \ Android数据库提取查询(Android database fetch query)

Android数据库提取查询(Android database fetch query)

private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "jobDiagnosis";
private static final int DATABASE_VERSION = 2;
Cursor cursor = null;
private static final String TABLE_DATA = "create table Job_Saved (" +
        "Id text not null," +
        "Title text not null," +
        "Location text not null," +
        "State text not null," +
        "Company text not null," +
        "Description text not null," +
        "Status text not null," +
        "Username text not null," +
        "Password text not null)";
private final Context context;
private DatabaseHelper dbHelper;
private SQLiteDatabase db;
private static DBAdapter instance;

private DBAdapter(Context c) {
    System.out.println("Constructor of DB Adapter...");
    this.context = c;
    System.out.println("Creating the object of db helper class..");
    try
    {
    dbHelper = new DatabaseHelper(context);
    dbHelper.getWritableDatabase();
    }
    catch (Exception e) {
        // TODO: handle exception
        Log.d("err", ""+e);
    }
}

public static DBAdapter getInstance(Context C) {
    if (null == instance) {
        instance = new DBAdapter(C);
    }
    return instance;
}

public void openReadableDatabase() throws SQLException {
    db = dbHelper.getReadableDatabase();
}

public void openWritableDatabase() throws SQLException {
    db = dbHelper.getWritableDatabase();

}

public void close() {
    dbHelper.close();   
}   
public long DeleteLocation(String name)
{
    return db.delete("Job_Saved", null, null);
}
public long insertlocation(String Id,String Title,String Location,String State,String Company,String Description,String value, String Username,String Password) {
    //DatabaseHelper d=new DatabaseHelper(DBAdapter.this);
    ContentValues initialValues = new ContentValues();
    initialValues.put("Id", Id);
    initialValues.put("Title", Title);
    initialValues.put("Location", Location);
    initialValues.put("State", State);
    initialValues.put("Company",Company);
    initialValues.put("Description", Description);
    initialValues.put("Status", value);
    initialValues.put("Username", Username);
    initialValues.put("Password", Password);
    return db.insert("Job_Saved", null, initialValues);
}
public ArrayList<Data> getAllData(){
    ArrayList<Data> arr = new ArrayList<Data>();
    Cursor c = db.query("Job_Saved", null, null, null, null, null, null);   
    if(c.getCount()>0){
        while(c.moveToNext()){
            Data f = new Data();
            f.setid(c.getString(0));
            f.setbusinessname(c.getString(1));
            f.setcityname(c.getString(2));
            f.setstatename(c.getString(3));
            f.setcompanyname(c.getString(4));
            f.setDesc(c.getString(5));
            f.setStatus(c.getString(6));
            f.setUser(c.getString(7));
            //f.setCharging(c.getString(8));
            arr.add(f);
        }

    }
    c.close();
    return arr;
}
public void updateDownload(String id  , String status)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put("status", status);
    db.update("Likes", initialValues, "id=?", new String[] {id});
}
public String getIdStatus(String id){
    String a="";
    Cursor c =  db.query("Likes", null, "id='" + id + "'", null, null, null,
            null);      
    if(c.getCount()>0){
        while(c.moveToNext())
        {
         a=c.getString(1);
        }

    }
    return a;
}

private class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        System.out.println("Constructor of DB Helper Class...");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("on create of database helper class..");

        try {
            // Creating Database...........................................
            db.execSQL(TABLE_DATA);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onOpen(SQLiteDatabase db) {
        // DBAdapter.this.db=db;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Log.w(TAG, "Upgrading database from version " + oldVersion
        // + " to "
        // + newVersion + ", which will destroy all old data");
        // db.execSQL("DROP TABLE IF EXISTS users");
        // onCreate(db);
    }
}

public String getFolderkeywordname(String string) {
    String index = "";
    Cursor c =  db.query("folders", new String[] { "keyword" }, "name='" + string + "'", null, null, null,
            null);      
    if(c.getCount()>0){
        while(c.moveToNext()){
            System.out.println("folder id is : " + index);
            index =  c.getString(0);

        }
    }
    c.close();
    return index;
}

}

这是我的数据库适配器类。 我还定义了一个getter和setter类,但我不知道从数据库中获取值所以请帮助我。

我也想使用fetch和delete查询

任何帮助表示赞赏。 先谢谢你。


private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "jobDiagnosis";
private static final int DATABASE_VERSION = 2;
Cursor cursor = null;
private static final String TABLE_DATA = "create table Job_Saved (" +
        "Id text not null," +
        "Title text not null," +
        "Location text not null," +
        "State text not null," +
        "Company text not null," +
        "Description text not null," +
        "Status text not null," +
        "Username text not null," +
        "Password text not null)";
private final Context context;
private DatabaseHelper dbHelper;
private SQLiteDatabase db;
private static DBAdapter instance;

private DBAdapter(Context c) {
    System.out.println("Constructor of DB Adapter...");
    this.context = c;
    System.out.println("Creating the object of db helper class..");
    try
    {
    dbHelper = new DatabaseHelper(context);
    dbHelper.getWritableDatabase();
    }
    catch (Exception e) {
        // TODO: handle exception
        Log.d("err", ""+e);
    }
}

public static DBAdapter getInstance(Context C) {
    if (null == instance) {
        instance = new DBAdapter(C);
    }
    return instance;
}

public void openReadableDatabase() throws SQLException {
    db = dbHelper.getReadableDatabase();
}

public void openWritableDatabase() throws SQLException {
    db = dbHelper.getWritableDatabase();

}

public void close() {
    dbHelper.close();   
}   
public long DeleteLocation(String name)
{
    return db.delete("Job_Saved", null, null);
}
public long insertlocation(String Id,String Title,String Location,String State,String Company,String Description,String value, String Username,String Password) {
    //DatabaseHelper d=new DatabaseHelper(DBAdapter.this);
    ContentValues initialValues = new ContentValues();
    initialValues.put("Id", Id);
    initialValues.put("Title", Title);
    initialValues.put("Location", Location);
    initialValues.put("State", State);
    initialValues.put("Company",Company);
    initialValues.put("Description", Description);
    initialValues.put("Status", value);
    initialValues.put("Username", Username);
    initialValues.put("Password", Password);
    return db.insert("Job_Saved", null, initialValues);
}
public ArrayList<Data> getAllData(){
    ArrayList<Data> arr = new ArrayList<Data>();
    Cursor c = db.query("Job_Saved", null, null, null, null, null, null);   
    if(c.getCount()>0){
        while(c.moveToNext()){
            Data f = new Data();
            f.setid(c.getString(0));
            f.setbusinessname(c.getString(1));
            f.setcityname(c.getString(2));
            f.setstatename(c.getString(3));
            f.setcompanyname(c.getString(4));
            f.setDesc(c.getString(5));
            f.setStatus(c.getString(6));
            f.setUser(c.getString(7));
            //f.setCharging(c.getString(8));
            arr.add(f);
        }

    }
    c.close();
    return arr;
}
public void updateDownload(String id  , String status)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put("status", status);
    db.update("Likes", initialValues, "id=?", new String[] {id});
}
public String getIdStatus(String id){
    String a="";
    Cursor c =  db.query("Likes", null, "id='" + id + "'", null, null, null,
            null);      
    if(c.getCount()>0){
        while(c.moveToNext())
        {
         a=c.getString(1);
        }

    }
    return a;
}

private class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        System.out.println("Constructor of DB Helper Class...");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("on create of database helper class..");

        try {
            // Creating Database...........................................
            db.execSQL(TABLE_DATA);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onOpen(SQLiteDatabase db) {
        // DBAdapter.this.db=db;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Log.w(TAG, "Upgrading database from version " + oldVersion
        // + " to "
        // + newVersion + ", which will destroy all old data");
        // db.execSQL("DROP TABLE IF EXISTS users");
        // onCreate(db);
    }
}

public String getFolderkeywordname(String string) {
    String index = "";
    Cursor c =  db.query("folders", new String[] { "keyword" }, "name='" + string + "'", null, null, null,
            null);      
    if(c.getCount()>0){
        while(c.moveToNext()){
            System.out.println("folder id is : " + index);
            index =  c.getString(0);

        }
    }
    c.close();
    return index;
}

}

This is my database adapter class. I have also defined a getter And setter class but i don't have any idea to fetch value from database So please help me.

I also want to use fetch and delete query

Any help is appreciated. Thank you in advance.


原文:https://stackoverflow.com/questions/19922694
更新时间:2023-07-12 13:07

最满意答案

您可以按values将df转换为numpy数组并reshape 。 然后你可以通过列表理解用范围设置新的列名:

print resultsDf

      0
0   100
1 -2800
2 -2800
3 -2800
0 -2800
1 -2800
2 -2900
3 -3000
0 -3000
1 -3000
2 -3000
3 -3000
0 -3000
1 -3000
2 -3000
3 -3000

df = pd.DataFrame((resultsDf.values).reshape((4, (resultsDf.values).shape[0]/4)))
df.columns = ['C' + str(i) for i in range(1, len(df.columns) + 1) ]

print df

     C1    C2    C3    C4
0   100 -2800 -2800 -2800
1 -2800 -2800 -2900 -3000
2 -3000 -3000 -3000 -3000
3 -3000 -3000 -3000 -3000

如果缺少最后一行(不将索引重复为其他行):

print resultsDf

        0
0     100
1   -2800
2   -2800
3   -2800
4   -2800
5   -2800
6   -2900
7   -3000
8   -3000
9   -3000
10  -3000
11  -3000
12  -3000
13  -3000
14  -3000
15  -3000
0     100
1   -2800
2   -2800
3   -2800
4   -2800
5   -2800
6   -2900
7   -3000
8   -3000
9   -3000
10  -3000
11  -3000
12  -3000
13  -3000
14  -3000
15  -3000
0   -3100
1   25500
#use all df without last two rows - resultsDf[:-2]
df = pd.DataFrame((resultsDf[:-2].values).reshape(16, resultsDf[:-2].values.shape[0]/16))
#append last two rows to new df
df = pd.concat([df, resultsDf[-2:]], axis=1)
df.columns = ['C' + str(i) for i in range(1, len(df.columns) + 1) ]

print df

      C1    C2     C3
0    100 -2800  -3100
1  -2800 -2800  25500
2  -2800 -2800    NaN
3  -2900 -3000    NaN
4  -3000 -3000    NaN
5  -3000 -3000    NaN
6  -3000 -3000    NaN
7  -3000 -3000    NaN
8    100 -2800    NaN
9  -2800 -2800    NaN
10 -2800 -2800    NaN
11 -2900 -3000    NaN
12 -3000 -3000    NaN
13 -3000 -3000    NaN
14 -3000 -3000    NaN
15 -3000 -3000    NaN

You can convert df to numpy array by values and reshape. then you can set new columns names by list comprehension with range:

print resultsDf

      0
0   100
1 -2800
2 -2800
3 -2800
0 -2800
1 -2800
2 -2900
3 -3000
0 -3000
1 -3000
2 -3000
3 -3000
0 -3000
1 -3000
2 -3000
3 -3000

df = pd.DataFrame((resultsDf.values).reshape((4, (resultsDf.values).shape[0]/4)))
df.columns = ['C' + str(i) for i in range(1, len(df.columns) + 1) ]

print df

     C1    C2    C3    C4
0   100 -2800 -2800 -2800
1 -2800 -2800 -2900 -3000
2 -3000 -3000 -3000 -3000
3 -3000 -3000 -3000 -3000

If you have last rows missing (not repeating indices as other rows):

print resultsDf

        0
0     100
1   -2800
2   -2800
3   -2800
4   -2800
5   -2800
6   -2900
7   -3000
8   -3000
9   -3000
10  -3000
11  -3000
12  -3000
13  -3000
14  -3000
15  -3000
0     100
1   -2800
2   -2800
3   -2800
4   -2800
5   -2800
6   -2900
7   -3000
8   -3000
9   -3000
10  -3000
11  -3000
12  -3000
13  -3000
14  -3000
15  -3000
0   -3100
1   25500
#use all df without last two rows - resultsDf[:-2]
df = pd.DataFrame((resultsDf[:-2].values).reshape(16, resultsDf[:-2].values.shape[0]/16))
#append last two rows to new df
df = pd.concat([df, resultsDf[-2:]], axis=1)
df.columns = ['C' + str(i) for i in range(1, len(df.columns) + 1) ]

print df

      C1    C2     C3
0    100 -2800  -3100
1  -2800 -2800  25500
2  -2800 -2800    NaN
3  -2900 -3000    NaN
4  -3000 -3000    NaN
5  -3000 -3000    NaN
6  -3000 -3000    NaN
7  -3000 -3000    NaN
8    100 -2800    NaN
9  -2800 -2800    NaN
10 -2800 -2800    NaN
11 -2900 -3000    NaN
12 -3000 -3000    NaN
13 -3000 -3000    NaN
14 -3000 -3000    NaN
15 -3000 -3000    NaN

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)