在SQLite数据库android中插入

在SQLite数据库android中插入,android,insert,android-sqlite,Android,Insert,Android Sqlite,我是安卓的新手。我对数据库中的insert语句有一些问题,当我运行应用程序时,这些值还没有被插入。请找个人帮忙 public class DatabaseAdapter extends SQLiteOpenHelper { // Database attributes public static final String DB_NAME = "MoneyManagerSystemTr"; public static final int DB_VERSION = 1; // Table attr

我是安卓的新手。我对数据库中的insert语句有一些问题,当我运行应用程序时,这些值还没有被插入。请找个人帮忙

public class DatabaseAdapter extends SQLiteOpenHelper {
// Database attributes
public static final String DB_NAME = "MoneyManagerSystemTr";
public static final int DB_VERSION = 1;

// Table attributes

public static final String TABLE_ACCOUNT = "account_table";

//Account Table
public static final String KEY_BANKNAME ="bankname";
public static final String KEY_TYPE = "type";
public static final String KEY_ACCNUM = "accnum";
public static final String KEY_BALANCE = "balance";
public static final String KEY_EXPIRYDATE = "expirydate";

@Override
public void onCreate(SQLiteDatabase db) {


    String AccountTable = "create table if not exists " + TABLE_ACCOUNT + " ( " + BaseColumns._ID + " integer primary key autoincrement, " 
            + KEY_BANKNAME + " text not null, "
            + KEY_TYPE + " text, "
            + KEY_ACCNUM + " text, "
            + KEY_BALANCE + " text, "
            + KEY_EXPIRYDATE + " text);";

    db.execSQL(AccountTable);

String ROW1 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Cash','','',0, '');";
    db.execSQL(ROW1);

    String ROW2 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Bank Account','','',0, '');";
    db.execSQL(ROW2);

    String ROW3 = "INSERT INTO " + TABLE_ACCOUNT + " Values ('Credit Card','','',0, '');";
    db.execSQL(ROW3);

换一行用引号将0括起来

您可以将
键\u BALANCE
取消标记为文本,但在此字段中输入的是整数值。这就是你得到的错误

 public long insert_table(String BANKNAME,String TYPE,
            String ACCNUM, String BALANCE,
            String EXPIRYDATE) {

    this.insertStmt.bindString(1, BANKNAME);
    this.insertStmt.bindString(2, TYPE);
    this.insertStmt.bindString(3, ACCNUM);
    this.insertStmt.bindString(4, BALANCE);
    this.insertStmt.bindString(5, EXPIRYDATE);

    return this.insertStmt.executeInsert();

    }
在尝试插入值时调用此方法

DataHelper dh = new DataHelper(this);
dh.insert_table("Bank Account","","","0","");

从insert语句中删除分号,并在0周围添加引号:

String ROW1 = "INSERT INTO " + TABLE_ACCOUNT + " ("
              + KEY_BANKNAME + ", " + KEY_TYPE + ", "
              + KEY_ACCNUM + ", " + KEY_BALANCE + ", "
              + KEY_EXPIRYDATE + ") Values ('Cash', '', '', '0', '')";
db.execSQL(ROW1);

更好的是,请注意上的建议并改用。

您可以使用
ContentValues
插入数据库

SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_NAME, VALUE); 
values.put(COL_NAME, VALUE);

// Inserting Row
db.insert(YOUR_TABLE, null, values);
1) 数据库助手

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String TAG = "DatabaseHelper";
public static final String DATABASE_NAME = "test.db";


public static final String TABLE_NAME_2 = "updates";


private Context context;
public static final String Trigger = "fk_insert_state";
public static final int DATABASE_VERSION = 2;



public static final String TABLE_2_CREATE = "Create table "
        + TABLE_NAME_2
        + " (_id integer primary key autoincrement, w_id text, title text, des text, date_text text, image_url text, video_url text,link text, con_type text, con_source text, timestamp integer, UNIQUE (_id) ON CONFLICT REPLACE)";


private static DatabaseHelper databasehelper;

public static DatabaseHelper getInstance(Context context) {
    if (databasehelper == null)
        databasehelper = new DatabaseHelper(context);
    return databasehelper;

}

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = context;

}

@Override
public void onCreate(SQLiteDatabase db) {


    db.execSQL(TABLE_2_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Util.customLog("Upgrade "
            + "Database has been updraded but we have'nt do anything");
}

 }
2) 数据库操作

 import android.content.ContentValues;

 public interface DatabaseOperation {
 public long insert(Object object);
 public int update(Object object);
 public int delete(Object object);
 ContentValues getContentValues(Object object);
 }
3) 数据类

public class UpdateData {

private int _id;
private String w_id;
private long timestamp;

public UpdateData(int _id, String w_id,  long timestamp) {
    super();
    this._id = _id;
    this.w_id = w_id;
    this.timestamp = timestamp;

}



public String getW_id() {
    return w_id;
}

public void setW_id(String w_id) {
    this.w_id = w_id;
}

public long getTimestamp() {
    return timestamp;
}

public void setTimestamp(long timestamp) {
    this.timestamp = timestamp;
}

public UpdateData() {
    super();
}

public String TableName() {
    return "updates";
}

public int get_id() {
    return _id;
}

public void set_id(int _id) {
    this._id = _id;
}

}
4) 数据导入

导入android.content.ContentValues;
导入android.content.Context;
导入android.database.Cursor;
导入android.database.sqlite.SQLiteDatabase;
公共类UpdateImpl实现数据库操作{
SQLITE数据库;
公共UpdateImpl(上下文){
DatabaseHelper DatabaseHelper=DatabaseHelper.getInstance(上下文);
database=databasehelper.getWritableDatabase();
}
@凌驾
公共长插入(对象){
UpdateData表=(UpdateData)对象;
long result=database.insert(table.TableName(),null,
这个.getContentValues(对象));
返回结果;
}
public void insertAll(ArrayList对象){
database.beginTransaction();
对于(UpdateData对象:对象){
UpdateData表=对象;
database.insert(table.TableName(),null,
这个.getContentValues(对象));
}
database.setTransactionSuccessful();
数据库。endTransaction();
}
@凌驾
公共整数更新(对象){
UpdateData表=(UpdateData)对象;
String[]wherergs={String.valueOf(table.get_id())};
返回更新(对象“\u id=?”,其中为rgs);
}
公共int更新(对象对象、字符串where子句、字符串[]wherergs){
UpdateData表=(UpdateData)对象;
int result=database.update(table.TableName(),
this.getContentValues(对象),where子句,wherergs);
Util.customLog(“更新结果-”+结果);
返回结果;
}
@凌驾
公共整数删除(对象){
UpdateData表=(UpdateData)对象;
String[]wherergs={String.valueOf(table.get_id())};
int result=database.delete(table.TableName(),“\u id=?”,wherergs);
Util.customLog(“删除结果-”+结果);
返回结果;
}
@凌驾
公共内容值getContentValues(对象){
UpdateData表=(UpdateData)对象;
ContentValues ContentValues=新ContentValues();
//contentValues.put(“_id”,table.get_id());
contentValues.put(“w_id”,table.getW_id());
contentValues.put(“timestamp”,table.getTimestamp());
返回contentvalue;
}
公共列表getAll(){
List itemList=new ArrayList();
String[]columnArray={“\u id,w\u id,timestamp”};
Cursor Cursor=database.query(DatabaseHelper.TABLE_NAME_2,
列数组,“con_type=“+””“+type+””和con_source=“+””“+source+””,null,null,null,“timestamp DESC”,null);
if(cursor.getCount()>0){
cursor.moveToFirst();
做{
UpdateData table=新的UpdateData();
table.set_id(cursor.getInt(cursor.getColumnIndex(“_id”));
table.setW_id(cursor.getString(cursor.getColumnIndex(“w_id”));
table.setTimestamp(cursor.getLong(cursor
.getColumnIndex(“时间戳”);
项目列表。添加(表);
}while(cursor.moveToNext());
cursor.close();
}否则{
Util.customLog(“getAll-未找到值”);
}
返回项目列表;
}
公共void deletess(字符串Id)
{
试一试{
database.delete(DatabaseHelper.TABLE_NAME_2,“cat_id=“+id,null”);
}
捕获(例外e){
}
}
public int getCount_CatNomiid(字符串w_id,字符串nomi_id){
int res=0;
String[]columnArray={“\u id,cat\u id,nomi\u id,status”};
Cursor Cursor=database.query(DatabaseHelper.TABLE_NAME_2,
列数组,“cat_id=“+””“+w_id+””和nomi_id=“+””“+nomi_id+””,null,null,
无效);
如果((cursor!=null)&&(cursor.getCount()>0)){
cursor.moveToFirst();
res=res+1;
}否则{
res=0;
}
如果(光标!=null){
cursor.close();
}
返回cursor.getCount();
}
公共字符串删除状态(字符串类别id、字符串名称id){
String result=“成功更新通知状态”;
字符串qry=“”“+cat_id+””和nomi_id=“+””“+nomi_id+””;
游标=数据库
.rawQuery(“删除”+DatabaseHelper.TABLE_NAME_2+)
+“其中cat_id=“+qry,null”);
if(cursor.getCount()>0){
cursor.moveToFirst();
}
cursor.close();
返回结果;
}
公共字符串updatestatus(int-id){
String result=“成功更新通知状态”;
字符串qry=“””+id+“”;
Cursor=database.rawQuery(“更新”
+DatabaseHelper.TABLE_NAME_2+“设置状态=“+””“+”Y“+””
+“其中_id=“+qry,null”);
Util.customLog(“updatequery:+”更新”
+DatabaseHelper.TABLE_NAME_2+“设置状态=“+”Y”
+“其中_id=“+id”);
if(cursor.getCount()>0){
cursor.moveToFirst();
}
cursor.close();
返回结果;
}
public void deleteAll(){
试一试{
database.delete(DatabaseHelper.TABLE_NAME_2,null,null);
删除(“sqlite_序列”,null,null);
}捕获(例外e){
e、 printStackTrace();
}
}
}
公共字符串updatedata2(ContentValues cv,int pass_id){
String result=“已成功更新通知状态”;
字符串qry=“””+pass_id+“”;
database.update(DatabaseHelper.TABLE_NAME_02,cv,“w_id”+“=”+qry,
无效);
返回结果;
}
ContentValues cv=新
 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.sqlite.SQLiteDatabase;

public class UpdateImpl implements DatabaseOperation {
SQLiteDatabase database;

public UpdateImpl(Context context) {
    DatabaseHelper databasehelper = DatabaseHelper.getInstance(context);
    database = databasehelper.getWritableDatabase();

}

@Override
public long insert(Object object) {
    UpdateData table = (UpdateData) object;
    long result = database.insert(table.TableName(), null,
            this.getContentValues(object));
    return result;
}

public void insertAll(ArrayList<UpdateData> objects){
    database.beginTransaction();
    for (UpdateData object : objects) {
        UpdateData table = object;
        database.insert(table.TableName(), null,
                this.getContentValues(object));
    }
    database.setTransactionSuccessful();
    database.endTransaction();
}

@Override
public int update(Object object) {
    UpdateData table = (UpdateData) object;
    String[] whereArgs = { String.valueOf(table.get_id()) };
    return update(object, "_id = ?", whereArgs);
}

public int update(Object object, String whereClause, String[] whereArgs) {
    UpdateData table = (UpdateData) object;
    int result = database.update(table.TableName(),
            this.getContentValues(object), whereClause, whereArgs);
    Util.customLog("Update Result - " + result);
    return result;
}

@Override
public int delete(Object object) {
    UpdateData table = (UpdateData) object;
    String[] whereArgs = { String.valueOf(table.get_id()) };
    int result = database.delete(table.TableName(), "_id = ?", whereArgs);
    Util.customLog("Delete Result - " + result);
    return result;
}

@Override
public ContentValues getContentValues(Object object) {
    UpdateData table = (UpdateData) object;
    ContentValues contentValues = new ContentValues();
    // contentValues.put("_id", table.get_id());
    contentValues.put("w_id", table.getW_id());
    contentValues.put("timestamp", table.getTimestamp());

    return contentValues;

}

public List getAll() {
    List<UpdateData> itemList = new ArrayList<UpdateData>();

    String[] columnArray = { "_id,w_id , timestamp" };
    Cursor cursor = database.query(DatabaseHelper.TABLE_NAME_2,
            columnArray, "con_type=" + "'"+type+"' AND con_source="+"'"+source+"'", null, null, null, "timestamp DESC", null);

    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        do {
            UpdateData table = new UpdateData();
            table.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            table.setW_id(cursor.getString(cursor.getColumnIndex("w_id")));
            table.setTimestamp(cursor.getLong(cursor
                    .getColumnIndex("timestamp")));

            itemList.add(table);
        } while (cursor.moveToNext());
        cursor.close();
    } else {
        Util.customLog("getAll - No value found");
    }
    return itemList;
}
public void deletess(String Id)
{
    try {

        database.delete(DatabaseHelper.TABLE_NAME_2, "cat_id="+Id, null);
    }
    catch(Exception e) {

    }
}

public int getCount_CatNomiid(String w_id,String nomi_id) {
    int res = 0;
    String[] columnArray = { "_id, cat_id, nomi_id ,status" };
    Cursor cursor = database.query(DatabaseHelper.TABLE_NAME_2,
            columnArray, "cat_id=" + "'" + w_id + "' AND nomi_id=" + "'"+ nomi_id + "'", null, null, null,
            null);
    if ((cursor != null) && (cursor.getCount() > 0)) {
        cursor.moveToFirst();
        res = res + 1;
    } else {
        res = 0;
    }
    if (cursor != null) {
        cursor.close();
    }
    return cursor.getCount();
}

public String deletestatus(String cat_id, String nomi_id) {
    String result = "Suceesfully Updated Status of notify";
    String qry = "'" + cat_id + "' AND nomi_id=" + "'"+ nomi_id + "'";
    Cursor cursor = database
            .rawQuery("delete " + DatabaseHelper.TABLE_NAME_2 + ""
                    + " where cat_id=" + qry, null);
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
    }
    cursor.close();
    return result;
}

public String updatestatus(int id) {
    String result = "Suceesfully Updated Status of notify";
    String qry = "'" + id + "'";
    Cursor cursor = database.rawQuery("update "
            + DatabaseHelper.TABLE_NAME_2 + " SET status=" + "'" + "Y" + "'"
            + " where _id=" + qry, null);
    Util.customLog("updatequery: " + "update "
            + DatabaseHelper.TABLE_NAME_2 + " SET status=" + "Y"
            + " where _id=" + id);
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
    }
    cursor.close();
    return result;
}

public void deleteAll() {
    try {
        database.delete(DatabaseHelper.TABLE_NAME_2, null, null);
        database.delete("sqlite_sequence", null, null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

public String updatedata2(ContentValues cv, int pass_id) {
    String result = "Successfully Updated Status of notify";

    String qry = "'" + pass_id + "'";

    database.update(DatabaseHelper.TABLE_NAME_02, cv, "w_id" + "=" + qry,
            null);

    return result;
}

 ContentValues cv = new ContentValues();
                cv.put("is_like", "N");
                AlbumsPhotosImpl albmImpl = new AlbumsPhotosImpl(
                        FullPhotoAlbumActivity.this);
                albmImpl.updatedata2(cv,
                        Integer.parseInt(photo_id_array.get(

                        position).toString()));
   protected class GetJury extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // pDialog.setMessage("Please wait...");
        // pDialog.setIndeterminate(false);
        // pDialog.setCancelable(true);
        // pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        String android_id = Secure.getString(getContentResolver(),
                Secure.ANDROID_ID);
        String w = "";

        HttpClient httpclient = new DefaultHttpClient();


        HttpPost httppost = new HttpPost(Constant.SERVER);


        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                    2);

            nameValuePairs.add(new BasicNameValuePair("f", "functionname"));
             nameValuePairs.add(new BasicNameValuePair("xyz",
             xyz));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response1 = httpclient.execute(httppost);

            w = EntityUtils.toString(response1.getEntity());

            // pDialog.dismiss();

        } catch (Exception e) {

            Log.v("error", e + "");
            e.printStackTrace();
        }

        return w;
    }

    @Override
    protected void onPostExecute(String jsonText) {

        try {
            long time = System.currentTimeMillis();
            Log.i("TIME_S", time + "");
            JSONObject jobject = new JSONObject(jsonText);

            String status = jobject.getString("status");

            if (status.equals("1")) {


               JSONArray event_json2 = new JSONArray();
                try {
                    event_json2 = jobject.getJSONArray("result");
                } catch (Exception e) {

                }

                // JSONObject jsonObject = jobject.getJSONObject("result");

                //for (int j = 0; j < event_json2.length(); j++) {

                //  JSONObject jsonObject = event_json2.getJSONObject(j);

                //}



                JSONObject event_json_res = new JSONObject();
                try {
                    event_json_res = jobject.getJSONObject("results");
                } catch (Exception e) {

                }

                JSONObject event_json_votedata = new JSONObject();
                try {
                    event_json_votedata = event_json_res.getJSONObject("votedata");
                } catch (Exception e) {

                }   


                UpdateImpl updateimpl = new UpdateImpl(SplaceActivity.this);
                updateimpl.deleteAll();


                Log.i("TIME_DB_RESET_DONE", time + "");
                // updates
                ArrayList<UpdateData> updateDataToBeInserted = new ArrayList<UpdateData>();
                Iterator<String> keys = event_json_updates.keys();
                while (keys.hasNext()) {

                    String i = keys.next();
                    JSONObject jsona = event_json_updates.getJSONObject(i);

                    String timestamp = jsona.getString("timestamp");


                    updateDataToBeInserted.add(new UpdateData(0, "0",Long.parseLong(timestamp)));

                }
                updateimpl.insertAll(updateDataToBeInserted);


            } else if (status.equals("0")) {

                // Util.show_error_dialog(LoginActivity.this,
                // "Username and Password does not match");

                // Util.show_error_dialog(context,
                // "Oops, something went wrong. Please try again after sometime.");
            }

            // pDialog.dismiss();

        } catch (Exception e) {

            Log.v("error", e + "");
            // pDialog.dismiss();
            Log.e("GetBearerTokenTask", "Error:" + e.getMessage());
        }
    }
    }
package com.example.lalit.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.method.HideReturnsTransformationMethod;
import android.util.Log;
import android.widget.Toast;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Currency;

/**
 * Created by lalit on 7/30/2015.
 */
public class HotOrNot {

  public final static String KEY_ROWID="_id";
    public final static String KEY_NAME="persion_name";
    public final static String KEY_HOTNESS="persion_hotness";
    public final static String KEY_SUB="OS";

    public final static String DATABASE_NAME="HotOrNotdb";
    public final static String DATABASE_TABLE="peopleTable";
    public final static int DATABASE_VERSION=1;

    public static Dbhelper ourHelper;
    public final Context ourContext;
    public SQLiteDatabase ourDatabase;

    private static final String DATABASE_CREATE = "create table peopleTable(_id integer primary key autoincrement, "
            + "persion_name text not null, persion_hotness text not null);";


    public class Dbhelper extends SQLiteOpenHelper{
         public Dbhelper(Context context)
         {
             super(context,DATABASE_NAME,null,DATABASE_VERSION);
         }

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


         /*   db.execSQL("CREATE TABLE" + DATABASE_NAME +"("+
             KEY_ROWID +"INTEGER PRIMARY KEY AUTOINCREMENT,"+
             KEY_NAME  +"TEXT NOT NULL,"+
             KEY_HOTNESS+"TEXT NOT NULL);"*/


             //);




        }

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

        }


    }
    public HotOrNot(Context c)
    {
        ourContext=c;
    }

    public HotOrNot open() throws SQLException
    {
        ourHelper=new Dbhelper(ourContext);
        ourDatabase=ourHelper.getWritableDatabase();
        return this;
    }
   public void close()
   {
        ourHelper.close();
   }
 public long createEntry(String name,String hotness)
 {
     ourDatabase.execSQL("INSERT INTO peopleTable (persion_name,persion_hotness) VALUES('Lalit','Kushwah')");
     ContentValues cv=new ContentValues();
      cv.put(KEY_NAME,name);
      cv.put(KEY_HOTNESS,hotness);

      return ourDatabase.insert(DATABASE_TABLE,null,cv);

 }
    public String getData()
    {
        String[] col=new String[]{KEY_ROWID,KEY_NAME,KEY_HOTNESS};
        Cursor c=ourDatabase.query(DATABASE_TABLE,col,null,null,null,null,null);
        String result="";
        int irow=c.getColumnIndex(KEY_ROWID);
        int iname=c.getColumnIndex(KEY_NAME);
        int ihot=c.getColumnIndex(KEY_HOTNESS);

        for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
        {
           result=result+c.getString(irow)+"  "+c.getString(iname)+"  "+c.getString(ihot)+ "\n";

        }



        return result;
    }
}