1. 程式人生 > >Kotlin 一鍵Sqlitel生成Kotlin實體類

Kotlin 一鍵Sqlitel生成Kotlin實體類

由於創作需要,所以自己寫了一個Sqlite一鍵轉Kotlin實體類的程式碼,方便以後使用!
以此記錄!
maven

<!--sqlite 版本3.7.2   -->
	 <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.7.2</version>
        </dependency>

程式碼

   //sqlite生成kotlin實體類
    fun getBean() {
        Class.forName("org.sqlite.JDBC");//載入驅動
        val connection: Connection=DriverManager.getConnection("jdbc:sqlite:sample.db")//設定sqlite連線字串
        var statement=connection!!.createStatement()
        val connection1: Connection=DriverManager.getConnection("jdbc:sqlite:sample.db")
        var statement1=connection1!!.createStatement()
        var tableRs = statement1!!.executeQuery("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
        while (tableRs!!.next()) {
            var rs = statement!!.executeQuery("PRAGMA TABLE_INFO (${tableRs.getString("name")})")
            var sBuild = StringBuilder("package cn.xstm.gim.dataBean\n\n")//包名可以在這裡設定
            sBuild.append("import java.util.*")
            sBuild.append("\n\n")
            sBuild.append("/**\n\t*自動生成,請檢查格式 \n*/")
            sBuild.append("\n\n")
            sBuild.append("class ${Utils_Tool.firstBig(tableRs!!.getString("name"))} {\n")
            while (rs!!.next()) {
                sBuild.append("\tvar ${rs!!.getString("name")}:${getSqliteType(rs!!.getString("type"), rs!!.getInt("notnull"))}\n")
            }
            sBuild.append("\n}")
            val file = File("src/main/java/cn/xstm/gim/dataBean/${firstBig(tableRs!!.getString("name"))}.kt")//檔案生成路徑可以再這裡更改
            println(file.absolutePath)
            if (!file.exists()) {
                file.createNewFile()
            }
            val fileWriter = FileWriter(file)
            fileWriter.write(sBuild.toString())
            fileWriter.flush()
            fileWriter.close()

        }
    }

    //開頭字元大寫
    fun firstBig(name:String): String {
        return name.substring(0, 1).toUpperCase() + name.substring(1);
    }

    //獲取sqlite對應的kotlin型別
    fun getSqliteType(type:String,notNull:Int):String{
        return if(type.indexOf("INT")!=-1){
            "Int${if(notNull==1) "=0" else{"?=null"}}"
        }else if(type.equals("TIME")||type.equals("DATE")||type.equals("DATETIME")){
            "Date${if(notNull==1)"=Date()" else{"?=null"}}"
        }else{
            "String${if(notNull==1)"=\"\"" else{"?=null"}}"
        }
    }