如何在android中的SQLite数据中导入CSV文件?

时间:2016-02-04 06:50:55

标签: android database sqlite

   public class MainActivity extends Activity {
    Context context;
SQLiteDatabase db;
    public static final String CONTACTS_TABLE_NAME = "contacts";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        db.execSQL(
                "create table contacts " +
                        "(id integer primary key, name text,dt1 text,dt2 text, dt3 text,)"

        );

        String mCSVfile = "contacts.csv";
        Log.e("shashank ", "" + mCSVfile);
        AssetManager manager = context.getAssets();
        InputStream inStream = null;
        try {
            inStream = manager.open(mCSVfile);
            Log.e("shashank inStream ", "" + inStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
        Log.e("shashank br ", "" + br);
        String line = "";
        String tableName = "contacts";
        String columns = "id, name, phone, email, discipline,place";
        String str1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
        String str2 = ");";
        Log.e("shashank ", "" + str1);
        Log.e("shashank ", "" + str2);


        db.beginTransaction();
        try {
            while ((line = br.readLine()) != null) {
                StringBuilder sb = new StringBuilder(str1);
                String[] str = line.split(",");
                sb.append("'" + str[0] + "',");
                sb.append(str[1] + "',");
                sb.append(str[2] + "',");
                sb.append(str[3] + "'");
                sb.append(str[4] + "'");
                sb.append(str2);
                db.execSQL(sb.toString());
            }
            db.setTransactionSuccessful();
            db.endTransaction();
        } catch (IOException e) {
        }

    }
    }
  • 初学者在android中。我想导入CSV文件并在SQLIte数据库中上传。请问我可以建议我。我应该在这个类中创建一个数据库。 **

get this link在这篇文章中如何创建db.this SQLiteDatabase db; ????

1 个答案:

答案 0 :(得分:1)

create table contacts声明中有一个额外的逗号。

您的列名与INSERT INTO查询中的列名不匹配。