【问题标题】:Is there any way to import CSV file into SQLite Database using Kotlin?有没有办法使用 Kotlin 将 CSV 文件导入 SQLite 数据库?
【发布时间】:2019-07-31 09:23:15
【问题描述】:

我需要将 csv 文件作为表格导入 sqlite 数据库。这个 csv 文件中有很多数据。我想知道是否有办法以 Kotlin 方式以编程方式导入如此多的数据。我将不胜感激任何回答和评论。

{已编辑} 我试图打开一个 csv 文件,但它显示“打开失败”但是 logcat 中没有显示错误。我不知道我在哪里做错了。这是我试过的代码。

DatabaseHelper 类

class DataBaseHelper(val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {

companion object{

    private val DATABASE_NAME = "CSV2SQL"
    private val DATABASE_VERSION = 1

    private val TABLE_NAME = "table1"
    private val COL_ID = "Id"
    private val COL_COMPANY = "Company"
    private val COL_PRODUCT = "Product"
    private val COL_PRICE = "Price"
}
    override fun onCreate(db: SQLiteDatabase) {
        val CREATE_PRODUCTS_TABLE = ("CREATE TABLE " +
                TABLE_NAME + "("
                + COL_ID + " INTEGER PRIMARY KEY," +
                COL_COMPANY + " TEXT" +
                COL_PRODUCT + "TEXT" +
                COL_PRICE + "TEXT" +")")
        db.execSQL(CREATE_PRODUCTS_TABLE)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
        onCreate(db)
    }

    fun getAllProducts(): java.util.ArrayList<HashMap<String, String>> {
        val proList: java.util.ArrayList<HashMap<String, String>>
        proList = java.util.ArrayList()
        val selectQuery = "SELECT  * FROM $TABLE_NAME"
        val db = this.writableDatabase
        val cursor = db.rawQuery(selectQuery, null)
        if (cursor.moveToFirst()) {
            do {
                //Id, Company,Name,Price
                val map = HashMap<String, String>()
                map["Id"] = cursor.getString(0)
                map["Company"] = cursor.getString(1)
                map["Name"] = cursor.getString(2)
                map["Price"] = cursor.getString(3)
                proList.add(map)
            } while (cursor.moveToNext())
        }

        return proList
    }



  }

MainActivity 类

 class MainActivity : ListActivity() {

    internal lateinit var lbl: TextView
    internal var db = DataBaseHelper(this)
    internal lateinit var btnimport: Button
    internal lateinit var lv: ListView
    internal lateinit var myList: ArrayList<HashMap<String, String>>
    val requestcode = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val txt = findViewById<TextView>(R.id.txtresulttext)
        val mas = findViewById<Button>(R.id.btnupload)
        lv = getListView()

        mas.setOnClickListener  {
            val fileintent = Intent(Intent.ACTION_GET_CONTENT)
            fileintent.type = "gagt/sdf"
            try {
                startActivityForResult(fileintent, requestcode)
            } catch (e: ActivityNotFoundException) {
                lbl.text = "No activity can handle picking a file. Showing alternatives."
            }
        }
        myList = db.getAllProducts()
        if (myList.size != 0) {
            val lv = getListView()
            var array = arrayOf("Company", "Name", "Price")
            val adapter = SimpleAdapter(this,myList,
                R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
            setListAdapter(adapter)
            lbl.text = ""
        }

    }

    override fun  onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (data == null)
            return
            if (requestCode <= requestcode){

            val filepath = data.data!!.path
            val db = db.getWritableDatabase()
            val tableName = "table1"
            db.execSQL("delete from $tableName")
            try {
                if (resultCode == Activity.RESULT_OK) {
                    try {
//                        db = DBHelper(applicationContext)
                        val file = FileReader(filepath!!)

                        val buffer = BufferedReader(file)
                        val contentValues = ContentValues()
                        var line = ""
                        db.beginTransaction()

                        while ({ line = buffer.readLine(); line }() != null) {

                            val str = line.split(",".toRegex(), 3)
                                .toTypedArray()  // defining 3 columns with null or blank field //values acceptance
                            //Id, Company,Name,Price
                            val company = str[0]
                            val Name = str[1]
                            val Price = str[2]


                            contentValues.put("Company", company)
                            contentValues.put("Name", Name)
                            contentValues.put("Price", Price)
                            db.insert(tableName, null, contentValues)
                            lbl.text = "Successfully Updated Database."
                        }
                        db.setTransactionSuccessful()
                        db.endTransaction()
                    } catch (e: IOException) {
                        if (db.inTransaction())
                            db.endTransaction()
                        val d = Dialog(this)
                        d.setTitle(e.message.toString() + "first")
                        d.show()
                        // db.endTransaction();
                    }

                } else {
                    if (db.inTransaction())
                        db.endTransaction()
                    val d = Dialog(this)
                    d.setTitle("Only CSV files allowed")
                    d.show()
                }
            } catch (ex: Exception) {
                if (db.inTransaction())
                    db.endTransaction()

                val d = Dialog(this)
                d.setTitle(ex.message.toString() + "second")
                d.show()
                // db.endTransaction();
            }

        }
        myList = db.getAllProducts()
        if (myList.size != 0) {
            val lv = getListView()
            var array = arrayOf("Company", "Name", "Price")
            val adapter = SimpleAdapter(this,myList,
                R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
            setListAdapter(adapter)
            lbl.text = "Data Imported"
        }
    }

这是错误信息, Open Failed

【问题讨论】:

  • 您说您“不知道从哪里开始”,但至少表明您可以打开文件并遍历 CSV 的行,并且可以打开 sqlite 数据库连接。如果你不能做这些事情,最好在询问之前单独研究这些事情。否则,这实际上是要求某人为您编写所有代码。
  • 代码看起来像 C#,而不是 Kotlin。这是帮助你的一大障碍。此外,如果您无法识别错误消息或更具体的代码不起作用的原因,那么很难提供帮助。你说这是因为你的 CSV 有很多行,但是代码循环遍历输入文件的所有行,所以这不应该是问题。请提供您尝试过的实际代码以及它不工作的确切原因,包括错误消息和所发生情况的描述。
  • 刚刚添加了我真正尝试过的 kotlin 代码,它无法打开 csv 文件。 @CPerkins
  • 我猜这是文件权限问题,但图像中看不到确切的错误。 logcat 可能没有详细信息,因为代码正在捕获异常并将其显示在对话框中......但它没有显示足够的细节。见stackoverflow.com/questions/36750664/…
  • 感谢您的帮助。现在我根据您提供的帖子使用“InputStreamReader”而不是“FileReader”,调试一些错误,现在一切都很好:) @CPerkins

标签: android sqlite csv android-studio kotlin


【解决方案1】:

将“读取文本类”的使用从“FileReader”更改为“InputStreamReader”。

class MainActivity : ListActivity() {

internal lateinit var lbl: TextView
internal lateinit var db: DataBaseHelper
internal lateinit var btnimport: Button
internal lateinit var lv: ListView
internal lateinit var myList: ArrayList<HashMap<String, String>>
val requestcode = 1

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    db = DataBaseHelper(this)
    lbl = TextView(this)
    lbl = findViewById<TextView>(R.id.txtresulttext)
    val mas = findViewById<Button>(R.id.btnupload)
    lv = getListView()



    mas.setOnClickListener  {
        val fileintent = Intent(Intent.ACTION_GET_CONTENT)
        fileintent.type = "text/csv"
        try {
            startActivityForResult(fileintent, requestcode)
        } catch (e: ActivityNotFoundException) {
            lbl.text = "No activity can handle picking a file. Showing alternatives."
        }
    }
    myList = db.getAllProducts()
    if (myList.size != 0) {
        val lv = getListView()
        var array = arrayOf("Company", "Product", "Price")
        val adapter = SimpleAdapter(this,myList,
            R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
        setListAdapter(adapter)
        lbl.text = ""
    }

}

override fun  onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (data == null)
        return
        if (requestCode <= requestcode){
        val filepath = data.data!!.path
            println(filepath)
            val inputStream = FileInputStream(filepath)//String? to InputString
            println(inputStream)
            val db = db.getWritableDatabase()
        val tableName = "table1"
        db.execSQL("delete from $tableName")
        try {
            println("gg")
            if (resultCode == Activity.RESULT_OK) {
                try {
                    val file = InputStreamReader(inputStream)//use InputStreamReader

                    val buffer = BufferedReader(file)
                    val contentValues = ContentValues()
                    db.beginTransaction()
                    while (true){
                        val line = buffer.readLine()
                        if(line==null) break
                        val str = line.split(",".toRegex(), 3)
                            .toTypedArray()  

                        val Company = str[0].toString()
                        val Product = str[1].toString()
                        val Price = str[2].toString()

                        contentValues.put("Company", Company)
                        contentValues.put("Product", Product)
                        contentValues.put("Price", Price)
                        db.insert(tableName, null, contentValues)

                        lbl.text = "Successfully Updated Database."
                    }

                    db.setTransactionSuccessful()
                    db.endTransaction()
                } catch (e: IOException) {
                    if (db.inTransaction())
                        db.endTransaction()
                    val d = Dialog(this)
                    d.setTitle(e.message.toString() + "first")
                    d.show()
                }

            } else {
                if (db.inTransaction())
                    db.endTransaction()
                val d = Dialog(this)
                d.setTitle("Only CSV files allowed")
                d.show()
            }
        } catch (ex: Exception) {
            if (db.inTransaction())
                db.endTransaction()

            val d = Dialog(this)
            d.setTitle(ex.message.toString() + "second")
            d.show()
        }

    }
    myList = db.getAllProducts()
    if (myList.size != 0) {
        val lv = getListView()
        var array = arrayOf("Company", "Product", "Price")
        val adapter = SimpleAdapter(this,myList,
            R.layout.v, array,intArrayOf(R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice))
        setListAdapter(adapter)
        lbl.text = "Data Imported"
    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 2012-05-04
    相关资源
    最近更新 更多