新建SQLite数据库的代码
时间: 2024-01-21 22:01:59 浏览: 79
数据库创建SQL代码
好的,下面是在Eclipse中新建SQLite数据库的代码示例:
1. 在"MyDatabaseHelper.java"中定义数据库的名称、版本号、表名以及列名等信息:
```java
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "mydatabase.db"; // 数据库名称
private static final int DB_VERSION = 1; // 数据库版本号
private static final String TABLE_NAME = "mytable"; // 表名
private static final String COLUMN_ID = "_id"; // 列名1
private static final String COLUMN_NAME = "name"; // 列名2
private static final String COLUMN_AGE = "age"; // 列名3
public MyDatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableSql = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " VARCHAR(20), " +
COLUMN_AGE + " INTEGER)";
db.execSQL(createTableSql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String dropTableSql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(dropTableSql);
onCreate(db);
}
}
```
2. 在MainActivity中实例化"MyDatabaseHelper.java",并调用getWritableDatabase()方法获取可写数据库对象,用于进行增删改查操作:
```java
public class MainActivity extends AppCompatActivity {
private SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
database = dbHelper.getWritableDatabase();
}
}
```
3. 将数据库文件从assets文件夹中复制到应用程序的data/data/package_name/databases目录下,以便应用程序能够访问该数据库文件:
```java
private void copyDatabase() throws IOException {
InputStream inputStream = getAssets().open("mydatabase.db");
String outFileName = getDatabasePath(DB_NAME).getPath();
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
```
以上是在Eclipse中新建SQLite数据库的代码示例,希望对您有所帮助。
阅读全文