我正在开发一个项目,我在网上看到了各种示例,他们使用Button和all来演示插入数据。我想手动插入数据。我创建了数据库但插入部分不知道。下面我发布了我迄今为止工作过的代码。
VivzHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Message;
import java.util.HashMap;
/**
* Created by Akash on 3/13/2016.
*/
public class VivzHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "hit_lib1";
private static final String TABLE_NAME = "books";
private static final int DATABASE_VERSION = 4;
private static final String UID = "_id";
private static final String Name = "Name";
private static final String ADDRESS = "Address";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+Name+" VARCHAR(25), "+ADDRESS+" VARCHAR(255));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
private Context context;
public VivzHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
this.context=context;
appscreator.com.mydatabase.Message.message(context, "Constructor Called");
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
appscreator.com.mydatabase.Message.message(context, "onCreate Called");
}
catch (SQLException e) {
appscreator.com.mydatabase.Message.message(context, "" + e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
try {
appscreator.com.mydatabase.Message.message(context, "onUpgrade Called");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (SQLException e) {
appscreator.com.mydatabase.Message.message(context, "" + e);
e.printStackTrace();
}
}
public void insertEntry()
{
try
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// values.put("Messsage", msg);
values.put("Name", Name);
values.put("Address", ADDRESS);
db.insert("TABLE_NAME ", null, values);
}
catch (Exception e)
{
}
}
}
Main_Activity.java
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
公共类MainActivity扩展了AppCompatActivity {
VivzHelper vivzHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vivzHelper= new VivzHelper(this);
SQLiteDatabase data = vivzHelper.getWritableDatabase();
}
答案 0 :(得分:1)
您只想插入5行?使用循环,只需调用插入数据的方法......
VivzHelper vivzHelper;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vivzHelper= new VivzHelper(this);
for (int i = 0; i < 5; i++) {
vivzHelper.insertEntry();
}
}