我需要将csv文件作为表格导入sqlite数据库。该csv文件中有很多数据。我想知道是否有一种方法可以通过Kotlin方式以编程方式导入大量数据。任何答复和评论,我将不胜感激。
{编辑} 我试图打开一个csv文件,但显示“打开失败”,但是logcat中没有显示错误。我不知道我在哪里犯了错误。这是我尝试的代码。
DatabaseHelper类
[{'N': 0, 'LT': 50, 'DATE': 2001}, {'N': 2, 'LT': 0, 'DATE': 2018}, {'N': 1, 'LT': 40, 'DATE': 2019}]
MainActivity类
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
}
}
这是错误消息, Open Failed
答案 0 :(得分:0)
将“读取文本类”的使用从“ 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"
}
}
}