android 插入多个值失败

6vl6ewon  于 2022-11-20  发布在  Android
关注(0)|答案(1)|浏览(113)

当有一个值时,它可以工作,但当有多个值时,它拒绝插入。所有变量都在类student中声明:

package com.example.termexam;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class rapp extends AppCompatActivity {

    EditText ed1r,ed2r;
    Button b1,b2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rateapp);

        ed1r = findViewById(R.id.name1);
        ed2r = findViewById(R.id.violate);

        b1 = findViewById(R.id.sbt1);
        b2 = findViewById(R.id.ratv1);

        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(rapp.this,vrate.class);
                startActivity(i);
            }
        });
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insert();
            }
        });
    }

    public void insert()
    {
        try
        {
            String name1 = ed1r.getText().toString();
            String violate = ed2r.getText().toString();

            SQLiteDatabase db = openOrCreateDatabase("SliteDb", Context.MODE_PRIVATE,null);
            db.execSQL("CREATE TABLE IF NOT EXISTS violate(id INTEGER PRIMARY KEY AUTOINCREMENT,name1 VARCHAR)");
            String sql = "insert into violate(name1)values(?)";

(((( this should be
  db.execSQL("CREATE TABLE IF NOT EXISTS violate(id INTEGER PRIMARY KEY AUTOINCREMENT,name1 VARCHAR,violate VARCHAR)");
          String sql = "insert into violate(name1,violate)values(?,?)"; )))))

            SQLiteStatement statement = db.compileStatement(sql);
            statement.bindString(1,name1);
            statement.execute();
            Toast.makeText(this,"Record addded", Toast.LENGTH_LONG).show();
            ed1r.setText("");
            ed2r.setText("");
            ed1r.requestFocus();
        }
        catch (Exception ex)
        {
            Toast.makeText(this,"Record Fail",Toast.LENGTH_LONG).show();
        }
    }
}
bis0qfac

bis0qfac1#

最好在单独的类中创建表,而不是在一个Activity中创建表,这样可以在其他Activity和片段中访问数据库。
这里是用于创建和插入的a link。还有check datatypes。例如VARCHAR可以声明为TEXT。

相关问题