首页 > 解决方案 > 无法插入到 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() 方法中,插入失败并被捕获。我的问题可能是什么?提前致谢。

标签: javaandroidsqliteandroid-sqlite

解决方案


您想在表中插入变量的值_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插入行的值。


推荐阅读