java - 无法插入到 SQLite 数据库
问题描述
我正在获取一个位置的纬度和经度信息并将它们添加到 SQLite。看起来我创建数据库没有问题,但我的插入不起作用。这是我的代码:
private GoogleMap mMap;
Button button;
double _lat,_lon;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
intent = getIntent();
_lat = intent.getDoubleExtra("yenie",0);
_lon = intent.getDoubleExtra("yenib",0);
button = findViewById(R.id.kaydet);
SQLiteDatabase database = this.openOrCreateDatabase("Konumlar",MODE_PRIVATE,null);
database.execSQL("CREATE TABLE IF NOT EXISTS knm (lat DOUBLE,lon DOUBLE)");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
database.execSQL("INSERT INTO knm (lat,lon) VALUES (_lat,_lon)");
Toast.makeText(getApplicationContext(),"sa",Toast.LENGTH_LONG);
}
catch (Exception e){
}
}
});
}
据我调试了解,在 onClick() 方法中,插入失败并被捕获。我的问题可能是什么?提前致谢。
解决方案
您想在表中插入变量的值_lat
,_lon
但您的 sql 语句改为使用它们的名称。
这样 SQLite 将名称视为当然不存在的列名,这会引发异常。
插入行的推荐方法是使用方法insert()
and ContentValues
:
ContentValues cv = new ContentValues();
cv.put("lat", _lat);
cv.put("lon", _lon);
int rowid = database.insert("knm", null, cv);
您可以检查 的值rowid
。
如果是-1
插入失败。
任何其他值都是rowid
插入行的值。
推荐阅读
- css - CSS 和 HTML 中的交叉淡入淡出幻灯片
- maven - Maven:使用詹金斯时不可解析的POM
- javascript - 您可以合并画布和视频元素并使用 mediarecorder 记录输出吗?
- ignite - 点燃自定义依赖支持
- r - 合并重复行并应用 Pivot_wider
- python - 转置然后解开一个 Numpy 数组不给出视图?
- python - 在 PySpark 中组合来自两个数据帧的两列
- python - 无法在 Windows 上安装 snowflake-connector-python
- javascript - Angular 2+浏览器控制台中的可调用函数
- r - 变量的平均值