Scala 连接sqlite数据库 jdbc

版权声明:Boomlee https://blog.csdn.net/BoomLee/article/details/83104606

什么是 SQLite?

SQLite是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。它是一个零配置的数据库,这意味着与其他数据库一样,您不需要在系统中配置。

就像其他数据库,SQLite 引擎不是一个独立的进程,可以按应用程序需求进行静态或动态连接。SQLite 直接访问其存储文件。

1.添加Maven

<!-- https://mvnrepository.com/artifact/org.xerial/sqlite-jdbc -->
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.25.2</version>
        </dependency>

2.连接数据库

object ScalaTest {

    def main(args: Array[String]) {

      Class.forName("org.sqlite.JDBC").newInstance()
      val con = DriverManager.getConnection("jdbc:sqlite::memory:")

      val  statement = con.createStatement
      // db路径
      val temp="C:\\Users\\Lee\\Desktop\\beijing.db"

      // 数据库起命名 tmpsqlite
      var attachsql = "ATTACH '"+temp+"' AS tmpsqlite"
      statement.executeUpdate(attachsql)
        
      //执行sql(该sql是查看当前db所有表)
      val citys = "select * from tmpsqlite.sqlite_master where type='table' order by name"
      val cityResult = statement.executeQuery(citys)
        
      //遍历结果集
      while(cityResult.next()){
      print(cityResult.getString("name"))
      }       

      //关闭连接  
      con.close()

    }


}

猜你喜欢

转载自blog.csdn.net/BoomLee/article/details/83104606
今日推荐