SpatiaLite.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- coding: utf-8 -*-
  2. __author__ = 'wanger'
  3. __date__ = '2024-08-27'
  4. __copyright__ = '(C) 2024 by siwei'
  5. __revision__ = '1.0'
  6. import sqlite3
  7. class SpatiaLiteUtils:
  8. def __init__(
  9. self,
  10. dbpath: str
  11. ):
  12. self.dbpath = dbpath
  13. # 连接到数据库
  14. self.conn = sqlite3.connect(dbpath)
  15. self.cursor = self.conn.cursor()
  16. self.conn.enable_load_extension(True)
  17. self.conn.execute("PRAGMA synchronous = OFF")
  18. self.conn.execute("PRAGMA cache_size = -20000") # In KB
  19. self.conn.execute("PRAGMA temp_store = MEMORY")
  20. self.conn.execute("SELECT load_extension('mod_spatialite');")
  21. print("mod_spatialite loaded successfully.")
  22. def execute(self, sql):
  23. self.cursor.execute(sql)
  24. rows = self.cursor.fetchall()
  25. return rows
  26. def executescript(self,sql):
  27. self.cursor.executescript(sql)
  28. print(f"Script executed successfully.{sql}")
  29. def enable_load_extension(self, bool):
  30. self.conn.enable_load_extension(bool)
  31. def queryCount(self, tablename):
  32. self.cursor.execute(f"SELECT count(1) FROM {tablename};")
  33. rows = self.cursor.fetchall()
  34. return rows[0][0]
  35. #重置数据库
  36. def resetDb(self):
  37. # 获取所有表名,排除系统表
  38. self.cursor.execute("""-- 删除所有表
  39. select 'drop table if exists ' || name || ';'
  40. from sqlite_master
  41. where type='table' and name not like 'sqlite_%' and name like '%topology%'
  42. union all
  43. -- 删除所有索引
  44. select 'drop index if exists ' || name || ';'
  45. from sqlite_master
  46. where type='index' and name like '%topology%'
  47. union all
  48. -- 删除所有视图
  49. select 'drop view if exists ' || name || ';'
  50. from sqlite_master
  51. where type='view' and name like '%temp%'
  52. union all
  53. -- 删除所有触发器
  54. select 'drop trigger if exists ' || name || ';'
  55. from sqlite_master
  56. where type='trigger' and name like '%topology%';""")
  57. tables = self.cursor.fetchall()
  58. # 循环删除每个表
  59. for sql in tables:
  60. self.cursor.execute(sql[0])
  61. # 提交更改并关闭连接
  62. self.conn.commit()
  63. def closeDb(self):
  64. self.cursor.close()
  65. self.conn.close()