以下代码是J2ME简单的数据库源码,提供给大家分享
package cn.hipha.util;
import javax.microedition.rms.RecordStore;
public class JmeDB {
private RecordStore rs = null;
public JmeDB() {
}
public JmeDB(String dbName) {
openDB(dbName);
}
public void openDB(String dbName) {
try {
rs = RecordStore.openRecordStore(dbName, true);
} catch (Exception e) {
}
}
public String getRecord(String name) throws Exception {
byte[] bytes = getRecord(name, 1);
if (bytes != null && bytes.length > 0)
return new String(bytes);
return "";
}
public byte[] getRecord(String name, int index) throws Exception {
RecordStore rss = getRecordSotre(name);
byte[] bytes = getRecord(rss, index);
closeRecordStore(rss);
return bytes;
}
private byte[] getRecord(RecordStore rs, int index) throws Exception {
if (rs == null) {
throw new Exception("Database desn't open!");
}
try {
if (rs.getNumRecords() >= index) {
byte[] byte1 = rs.getRecord(index);
return byte1;
}
} catch (Exception e) {
}
return new byte[0];
}
public void setRecord(String name, String record) throws Exception {
setRecord(name, 1, record);
}
public void setRecord(String name, int index, String record)
throws Exception {
byte[] data = record.getBytes("UTF-8");
setRecord(name, index, data);
}
public void setRecord(String name, byte[] data)throws Exception {
setRecord(name, 1, data);
}
public void setRecord(String name, int index, byte[] data)throws Exception {
RecordStore rss = getRecordSotre(name);
setRecord(rss, index, data);
closeRecordStore(rss);
}
protected boolean hasRecord(RecordStore rs, String name) throws Exception {
if (rs == null) {
throw new Exception("Database desn't open!");
}
boolean flag = false;
for (int i = 1; i <= rs.getNumRecords(); i++) {
byte[] bytes = getRecord(rs, i);
if (bytes != null && bytes.length > 0) {
String temp = new String(bytes);
if (name.trim().equals(temp.trim())) {
flag = true;
break;
}
}
}
return flag;
}
private RecordStore getRecordSotre(String name) throws Exception {
if (hasRecord(rs, name)) {
return RecordStore.openRecordStore(name, false);
} else {
byte[] data = name.getBytes("UTF-8");
setRecord(rs, rs.getNextRecordID(), data);
return RecordStore.openRecordStore(name, true);
}
}
private void setRecord(RecordStore rs, int index, byte[] data)
throws Exception {
if (rs == null) {
throw new Exception("Database desn't open!");
}
try {
if (data != null) {
int id = rs.getNextRecordID();
if (id <= index) {
rs.addRecord(data, 0, data.length);
} else {
rs.setRecord(index, data, 0, data.length);
}
}
} catch (Exception e) {
}
}
public void closeDB() {
closeRecordStore(rs);
}
private void closeRecordStore(RecordStore rs){
if (rs != null) {
try {
rs.closeRecordStore();
} catch (Exception e) {
}
}
}
}