it-swarm.com.ru

Как вставить значение в базу данных, используя sqlite в Android?

Подскажите, пожалуйста, как вставить значение в базу данных. Я только начал разрабатывать в Android не так много опыта.

Я просто создаю один класс information, где я создаю получатель и установщик поля имени . Package com.example.database_example;

package com.example.database_example;

public class Information {

    String name;
    public Information(String name) {
        // TODO Auto-generated constructor stub
        this.name=name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Теперь я создаю другой класс базы данных, в который я хочу добавить метод вставки и читать данные из базы данных.

package com.example.database_example;

import Android.content.ContentValues;
import Android.content.Context;
import Android.database.sqlite.SQLiteDatabase;
import Android.database.sqlite.SQLiteDatabase.CursorFactory;
import Android.database.sqlite.SQLiteOpenHelper;

public class DataBaseExample extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;

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

    // Contacts table name
    private static final String TABLE_Name= "Name";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";

    public DataBaseExample(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String createTable= "CREATE TABLE " + TABLE_Name+"("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
                + ")";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
         db.execSQL("DROP TABLE IF EXISTS " + TABLE_Name);

            // Create tables again
            onCreate(db);
    }

    public boolean insertname(Information information) {

        boolean createSuccessful = false;

        ContentValues values = new ContentValues();

      //  values.put(KEY_ID, information.getId());
        values.put(KEY_NAME, information.getName());

        SQLiteDatabase db = this.getWritableDatabase();

        createSuccessful = db.insert(TABLE_Name, null, values) > 0;
        db.close();

        return createSuccessful;
    }

}

Main File

package com.example.database_example;

import Android.os.Bundle;
import Android.app.Activity;
import Android.view.Menu;

public class MainActivity extends Activity {

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

        Information inf=new Information("naveen");
        DataBaseExample dbx=new DataBaseExample(MainActivity.this);
        dbx.insertname(inf);
    }

LogCat

09-24 07:25:07.138: I/Database(392): sqlite returned: error code = 1, msg = near ")": syntax error
09-24 07:25:07.138: E/Database(392): Failure 1 (near ")": syntax error) on 0x2a7080 when preparing 'CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)'.
09-24 07:25:07.148: D/AndroidRuntime(392): Shutting down VM
09-24 07:25:07.148: W/dalvikvm(392): threadid=1: thread exiting with uncaught exception (group=0x40015560)
09-24 07:25:07.158: E/AndroidRuntime(392): FATAL EXCEPTION: main
09-24 07:25:07.158: E/AndroidRuntime(392): Java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database_example/com.example.database_example.MainActivity}: Android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.app.ActivityThread.performLaunchActivity(ActivityThread.Java:1647)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.app.ActivityThread.handleLaunchActivity(ActivityThread.Java:1663)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.app.ActivityThread.access$1500(ActivityThread.Java:117)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.app.ActivityThread$H.handleMessage(ActivityThread.Java:931)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.os.Handler.dispatchMessage(Handler.Java:99)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.os.Looper.loop(Looper.Java:123)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.app.ActivityThread.main(ActivityThread.Java:3683)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Java.lang.reflect.Method.invokeNative(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Java.lang.reflect.Method.invoke(Method.Java:507)
09-24 07:25:07.158: E/AndroidRuntime(392):  at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:839)
09-24 07:25:07.158: E/AndroidRuntime(392):  at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:597)
09-24 07:25:07.158: E/AndroidRuntime(392):  at dalvik.system.NativeStart.main(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392): Caused by: Android.database.sqlite.SQLiteException: near ")": syntax error: CREATE TABLE Name(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.Java:1763)
09-24 07:25:07.158: E/AndroidRuntime(392):  at com.example.database_example.DataBaseExample.onCreate(DataBaseExample.Java:34)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.Java:126)
09-24 07:25:07.158: E/AndroidRuntime(392):  at com.example.database_example.DataBaseExample.insertname(DataBaseExample.Java:55)
09-24 07:25:07.158: E/AndroidRuntime(392):  at com.example.database_example.MainActivity.onCreate(MainActivity.Java:18)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.app.Instrumentation.callActivityOnCreate(Instrumentation.Java:1047)
09-24 07:25:07.158: E/AndroidRuntime(392):  at Android.app.ActivityThread.performLaunchActivity(ActivityThread.Java:1611)
09-24 07:25:07.158: E/AndroidRuntime(392):  ... 11 more**
6
user944513

Ваш метод вставки в Android sqlite может выглядеть следующим образом:

public boolean create(Information information) {

    boolean createSuccessful = false;

    ContentValues values = new ContentValues();

    values.put(KEY_NAME, information.getName());

    SQLiteDatabase db = this.getWritableDatabase();

    createSuccessful = db.insert(tableName, null, values) > 0;
    db.close();

    return createSuccessful;
}

Его можно добавить в ваш класс DataBaseExample.

Вы можете использовать его таким образом в своей деятельности или где угодно.

Information information = new Information(); 
information.setName("naveen"); 

if(new DataBaseExample().create(information)){
    Log.v(TAG, "save ok.");
}else{
    Log.v(TAG, "save failed.");
}

Смотрите здесь для более простых примеров.

6
Emkey
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();

values.put("Messsage", msg);
values.put("Name", SenderName);
values.put("GroupName", Groupname);

db.insert("TableName", null, values);

Для получения более подробной информации нажмите здесь http://androiddhina.blogspot.in/2015/04/insert-value-in-database-using-sqlite.html

3
Dhina k

Первая ошибка из-за лишней запятой, которую вы поместили в строку createTable после определения последнего столбца KEY_NAME+" TEXT," 

String createTable= "CREATE TABLE " + TABLE_Name+"("
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
            + ")";

правильная форма выглядит следующим образом:

String createTable= "CREATE TABLE " + TABLE_Name+"("
            + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT"
            + ")";
1
Elham Kohestani

Используйте ниже код

mSQLiteDatabase = getWritableDatabase(); //To insert we need to writable //database. If database is not created/opened it will do the job.
ContentValues contentValues = new ContentValues();
contentValues.put(key1,value1);
contentValues.put(key2,value2);
contentValues.put(key3,value3);
//...put the value for all the required colums of a row.....

long rowInserted = mSQLiteDatabase.insert(tablename,"",contentValues);
mSQLiteDatabase.close();//This is very important to close.Never forget this.
if(rowInserted != -1) {
//Insert success.
} else {
//Inser failed.
}
1
Durgesh
package com.example.hostelmangement;
import Java.util.ArrayList;
import Java.util.List;
import org.Apache.commons.logging.Log;
import Android.content.ContentValues;
import Android.content.Context;
import Android.database.Cursor;
import Android.database.sqlite.SQLiteDatabase;
public class DataBase  {
 DataBaseHelper database;
 int a=0;
 public DataBase(Context con)
         {

           database=new DataBaseHelper(con,"jojo", null,1);
         }
void insertData(String joindate, String name, String fathername, String dateofbirth, String housename, String houseplace, String housepin, String blood, String mobile, String email, String company, String companyplace, String companyphone, String companypin, String rent, String imgphoto, String imgproof)
{
    SQLiteDatabase sqld=database.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put("join_date", joindate);
    cv.put("name", name);
    cv.put("father_name", fathername);      
    cv.put("date_of_birth", dateofbirth);                           
    cv.put("house_name", housename);
    cv.put("place", houseplace);
    cv.put("pin_no", housepin);
    cv.put("blood_group", blood);      
    cv.put("mobile", mobile);                           
    cv.put("email", email);
    cv.put("company", company);
    cv.put("company_place", companyplace);
    cv.put("company_phone", companyphone);
    cv.put("company_pin", companypin);      
    cv.put("rent", rent); 
    cv.put("pending",a+"");
    cv.put("status", "a");
    cv.put("photo",imgphoto); 
    cv.put("proof",imgproof); 
    sqld.insert("demo", null,cv);  
}
public List<User> getDetails()
{
    List<User> ar=new ArrayList<User>();
    SQLiteDatabase sqldg=database.getReadableDatabase();
    Cursor cur=sqldg.rawQuery("select * from demo where status='a' order by name asc" , null);
    if(cur!=null)
    {
        if(cur.moveToFirst())
        {
            do
            {
                User user=new User();
                user.setId(cur.getInt(0));
                user.setJoindate(cur.getString(1));
                user.setName(cur.getString(2));
                user.setFathername(cur.getString(3));
                user.setDateofbirth(cur.getString(4));
                user.setHousename(cur.getString(5));
                user.setPlace(cur.getString(6));
                user.setPinno(cur.getString(7));
                user.setBloodgroup(cur.getString(8));
                user.setMobile(cur.getString(9));
                user.setEmail(cur.getString(10));
                user.setCompany(cur.getString(11));
                user.setCompanyplace(cur.getString(12));
                user.setCompanyphone(cur.getString(13));
                user.setCompanypin(cur.getString(14));
                user.setRent(cur.getString(15));
                user.setPhoto(cur.getString(18));
                user.setProof(cur.getString(19));
                ar.add(user);

            }
            while(cur.moveToNext());
        }
    }

    return ar;
}
public List<User> getDetailsforview(int memberid)
{
    List<User> ar=new ArrayList<User>();
    SQLiteDatabase sqldg=database.getReadableDatabase();
    Cursor cur=sqldg.rawQuery("select * from demo where id="+memberid , null);
    if(cur!=null)
    {
        if(cur.moveToFirst())
        {
            do
            {
                User user=new User();
                user.setId(cur.getInt(0));
                user.setJoindate(cur.getString(1));
                user.setName(cur.getString(2));
                user.setFathername(cur.getString(3));
                user.setDateofbirth(cur.getString(4));
                user.setHousename(cur.getString(5));
                user.setPlace(cur.getString(6));
                user.setPinno(cur.getString(7));
                user.setBloodgroup(cur.getString(8));
                user.setMobile(cur.getString(9));
                user.setEmail(cur.getString(10));
                user.setCompany(cur.getString(11));
                user.setCompanyplace(cur.getString(12));
                user.setCompanyphone(cur.getString(13));
                user.setCompanypin(cur.getString(14));
                user.setRent(cur.getString(15));
                user.setPhoto(cur.getString(18));
                user.setProof(cur.getString(19));
                ar.add(user);

            }
            while(cur.moveToNext());
        }
    }

    return ar;
}
public List<User> getDateSort()
{
    List<User> ar=new ArrayList<User>();
    SQLiteDatabase sqldg=database.getReadableDatabase();
    //Cursor cur=sqldg.rawQuery("select * from demo order by join_date asc", null);
    Cursor cur=sqldg.rawQuery("select * from demo where status='a' order by name asc", null);
    if(cur!=null)
    {
        if(cur.moveToFirst())
        {
            do
            {

                User user=new User();
                user.setId(cur.getInt(0));
                String date=cur.getString(1);
                String date1=date.substring(8, 10);
                user.setJoindate(date1);
                user.setName(cur.getString(2));
                user.setFathername(cur.getString(3));
                user.setDateofbirth(cur.getString(4));
                user.setHousename(cur.getString(5));
                user.setPlace(cur.getString(6));
                user.setPinno(cur.getString(7));
                user.setBloodgroup(cur.getString(8));
                user.setMobile(cur.getString(9));
                user.setEmail(cur.getString(10));
                user.setCompany(cur.getString(11));
                user.setCompanyplace(cur.getString(12));
                user.setCompanyphone(cur.getString(13));
                user.setCompanypin(cur.getString(14));
                user.setRent(cur.getString(15));
                user.setPending(cur.getInt(16));
                user.setPhoto(cur.getString(18));
                user.setProof(cur.getString(19));
                ar.add(user);

            }
            while(cur.moveToNext());
        }
    }

    return ar;
}
public List<User> deactiveMembers() {

    List<User> ar=new ArrayList<User>();
    SQLiteDatabase sqldg=database.getReadableDatabase();
    Cursor cur=sqldg.rawQuery("select * from demo where status='d' order by name asc", null);
    if(cur!=null)
    {
        if(cur.moveToFirst())
        {
            do
            {
                User user=new User();
                user.setId(cur.getInt(0));
                user.setJoindate(cur.getString(1));
                user.setName(cur.getString(2));
                user.setFathername(cur.getString(3));
                user.setDateofbirth(cur.getString(4));
                user.setHousename(cur.getString(5));
                user.setPlace(cur.getString(6));
                user.setPinno(cur.getString(7));
                user.setBloodgroup(cur.getString(8));
                user.setMobile(cur.getString(9));
                user.setEmail(cur.getString(10));
                user.setCompany(cur.getString(11));
                user.setCompanyplace(cur.getString(12));
                user.setCompanyphone(cur.getString(13));
                user.setCompanypin(cur.getString(14));
                user.setRent(cur.getString(15));
                user.setPhoto(cur.getString(18));
                user.setProof(cur.getString(19));
                ar.add(user);

            }
            while(cur.moveToNext());
        }
    }

    return ar;

}
public void Update(String joindate, String name, String fathername, String dateofbirth, String housename, String houseplace, String housepin, String blood, String mobile, String email, String company, String companyplace, String companyphone, String companypin, String rent, int id, String imgphoto, String imgproof)
{
    SQLiteDatabase sqld=database.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put("join_date", joindate);
    cv.put("name", name);
    cv.put("father_name", fathername);      
    cv.put("date_of_birth", dateofbirth);                           
    cv.put("house_name", housename);
    cv.put("place", houseplace);
    cv.put("pin_no", housepin);
    cv.put("blood_group", blood);      
    cv.put("mobile", mobile);                           
    cv.put("email", email);
    cv.put("company", company);
    cv.put("company_place", companyplace);
    cv.put("company_phone", companyphone);
    cv.put("company_pin", companypin);      
    cv.put("rent", rent);
    cv.put("photo", imgphoto);
    cv.put("proof", imgproof);
    sqld.update("demo",cv,"id="+id, null);
}
public void pendinUpdate(int pending, int lastamount)
{
    SQLiteDatabase sqld=database.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put("pending",lastamount);
    sqld.update("demo",cv,"id="+pending, null);
}
public void deleteUpdate(int id)
{
    SQLiteDatabase sqld=database.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put("status","d");
    sqld.update("demo",cv,"id="+id, null);
}
public void activate(int id)
{
    SQLiteDatabase sqld=database.getWritableDatabase();
    ContentValues cv=new ContentValues();
    cv.put("status","a");
    sqld.update("demo",cv,"id="+id, null);
}

}

0
jojo