You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用创建SQLite数据库时崩溃求助(附代码)

解决你的Android数据库创建崩溃问题

嘿,我一眼就揪出了导致崩溃的核心问题,还有几个能让代码更安全的优化点,咱们一步步来理清楚:

问题1:SQL关键字冲突

你创建表的语句里用了order作为字段名,但ORDER是SQLite的保留关键字,直接使用会触发语法错误,导致数据库初始化失败崩溃。

修复方案

两种可选方式,选一个你觉得顺手的:

// 方案1:换个无冲突的字段名(推荐,更直观)
String c_query="create table if not exists clients(sname text, add text, order_desc text, price text, ddate text)";
// 方案2:用反引号包裹关键字,告诉SQLite这是普通字段名
String c_query="create table if not exists clients(sname text, add text, `order` text, price text, ddate text)";

问题2:SQL注入风险与语法隐患

你直接用字符串拼接构造插入语句,不仅有严重的SQL注入风险,要是用户输入里带了单引号(比如O'Neil),还会再次触发语法错误导致崩溃。

修复方案

用Android官方推荐的ContentValues来安全插入数据,既规避风险又能避免语法问题:

b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String ssname=sname.getText().toString();
        String sadd=add.getText().toString();
        String sorder=order.getText().toString();
        String sprice=price.getText().toString();
        String sddate=ddate.getText().toString();

        // 用ContentValues封装数据
        ContentValues values = new ContentValues();
        values.put("sname", ssname);
        values.put("add", sadd);
        // 如果选了方案1的字段名,这里要改成"order_desc"
        values.put("`order`", sorder); 
        values.put("price", sprice);
        values.put("ddate", sddate);

        // 执行插入,还能判断是否成功
        long insertResult = db.insert("clients", null, values);
        if(insertResult != -1){
            Toast.makeText(getBaseContext(),"Record Inserted",Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getBaseContext(),"Insert Failed",Toast.LENGTH_LONG).show();
        }
    }
});

额外小提醒

  • 记得在Activity销毁时关闭数据库连接,避免资源泄漏:db.close();(可以放在onDestroy()方法里)
  • 字段名add也是SQL关键字,建议换成address这类清晰无冲突的名称,省得后面再踩坑。

内容的提问来源于stack exchange,提问作者H.Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:04:22