看分享,阅见世界,分享此刻。是一个整理、分享,搜索的网站。智阅无界,洞见未来。
  • 聚好看
  • 文章
  • 专题
  • 文章
  • 登录
  • 注册
计科知识库 计科知识库 24天前

用php写一个执行sqlite3的安全函数 全部增删改查

sqlite3 php
  1. db = new SQLite3($databasePath);
  2. $this->db->enableExceptions(true);
  3. // 设置WAL模式提升性能
  4. $this->db->exec('PRAGMA journal_mode=WAL');
  5. $this->db->exec('PRAGMA synchronous=NORMAL');
  6. $this->db->exec('PRAGMA foreign_keys=ON');
  7. } catch (Exception $e) {
  8. $this->error = "数据库连接失败: " . $e->getMessage();
  9. throw new Exception($this->error);
  10. }
  11. }
  12. /**
  13. * 安全查询 - 返回多条记录
  14. */
  15. public function safeQuery($sql, $params = []) {
  16. try {
  17. $stmt = $this->db->prepare($sql);
  18. if (!$stmt) {
  19. throw new Exception("SQL预处理失败");
  20. }
  21. // 绑定参数
  22. $this->bindParams($stmt, $params);
  23. $result = $stmt->execute();
  24. $rows = [];
  25. while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
  26. $rows[] = $row;
  27. }
  28. return $rows;
  29. } catch (Exception $e) {
  30. $this->error = "查询失败: " . $e->getMessage();
  31. return false;
  32. }
  33. }
  34. /**
  35. * 安全查询 - 返回单条记录
  36. */
  37. public function safeQuerySingle($sql, $params = []) {
  38. try {
  39. $stmt = $this->db->prepare($sql);
  40. if (!$stmt) {
  41. throw new Exception("SQL预处理失败");
  42. }
  43. $this->bindParams($stmt, $params);
  44. $result = $stmt->execute();
  45. return $result->fetchArray(SQLITE3_ASSOC);
  46. } catch (Exception $e) {
  47. $this->error = "查询失败: " . $e->getMessage();
  48. return false;
  49. }
  50. }
  51. /**
  52. * 安全执行 - 用于INSERT, UPDATE, DELETE
  53. */
  54. public function safeExecute($sql, $params = []) {
  55. try {
  56. $this->db->exec('BEGIN TRANSACTION');
  57. $stmt = $this->db->prepare($sql);
  58. if (!$stmt) {
  59. throw new Exception("SQL预处理失败");
  60. }
  61. $this->bindParams($stmt, $params);
  62. $result = $stmt->execute();
  63. $this->db->exec('COMMIT');
  64. return [
  65. 'success' => true,
  66. 'changes' => $this->db->changes(),
  67. 'lastInsertId' => $this->db->lastInsertRowID()
  68. ];
  69. } catch (Exception $e) {
  70. $this->db->exec('ROLLBACK');
  71. $this->error = "执行失败: " . $e->getMessage();
  72. return false;
  73. }
  74. }
  75. /**
  76. * 批量插入数据
  77. */
  78. public function batchInsert($table, $data) {
  79. if (empty($data)) {
  80. return false;
  81. }
  82. try {
  83. $this->db->exec('BEGIN TRANSACTION');
  84. $columns = array_keys($data[0]);
  85. $placeholders = ':' . implode(', :', $columns);
  86. $sql = "INSERT INTO $table (" . implode(', ', $columns) . ") VALUES ($placeholders)";
  87. $stmt = $this->db->prepare($sql);
  88. if (!$stmt) {
  89. throw new Exception("SQL预处理失败");
  90. }
  91. $insertedRows = 0;
  92. foreach ($data as $row) {
  93. $this->bindParams($stmt, $row);
  94. if ($stmt->execute()) {
  95. $insertedRows++;
  96. }
  97. $stmt->reset();
  98. }
  99. $this->db->exec('COMMIT');
  100. return $insertedRows;
  101. } catch (Exception $e) {
  102. $this->db->exec('ROLLBACK');
  103. $this->error = "批量插入失败: " . $e->getMessage();
  104. return false;
  105. }
  106. }
  107. /**
  108. * 绑定参数辅助方法
  109. */
  110. private function bindParams($stmt, $params) {
  111. foreach ($params as $key => $value) {
  112. // 确定参数类型
  113. if (is_int($value)) {
  114. $type = SQLITE3_INTEGER;
  115. } elseif (is_float($value)) {
  116. $type = SQLITE3_FLOAT;
  117. } elseif (is_null($value)) {
  118. $type = SQLITE3_NULL;
  119. } else {
  120. $type = SQLITE3_TEXT;
  121. }
  122. $stmt->bindValue(is_int($key) ? $key + 1 : ":$key", $value, $type);
  123. }
  124. }
  125. /**
  126. * 获取错误信息
  127. */
  128. public function getError() {
  129. return $this->error;
  130. }
  131. /**
  132. * 关闭数据库连接
  133. */
  134. public function close() {
  135. if ($this->db) {
  136. $this->db->close();
  137. }
  138. }
  139. public function __destruct() {
  140. $this->close();
  141. }
  142. }
  143. <code_end>
  144. <code_start>
  145. project_name=php_sqlite3_operations
  146. filename=example_usage.php
  147. title=使用示例和测试脚本
  148. entrypoint=true
  149. runnable=true
  150. project_final_file=true
  151. // 使用示例
  152. require_once 'SQLite3SafeOperations.php';
  153. try {
  154. // 创建数据库操作实例
  155. $dbOps = new SQLite3SafeOperations('test.db');
  156. // 创建测试表
  157. $createTable = "
  158. CREATE TABLE IF NOT EXISTS users (
  159. id INTEGER PRIMARY KEY AUTOINCREMENT,
  160. username TEXT NOT NULL UNIQUE,
  161. email TEXT NOT NULL,
  162. age INTEGER,
  163. created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  164. )
  165. ";
  166. $dbOps->safeExecute($createTable);
  167. // 示例1: 插入数据
  168. $insertData = [
  169. 'username' => 'john_doe',
  170. 'email' => 'john@example.com',
  171. 'age' => 25
  172. ];
  173. $result = $dbOps->safeExecute(
  174. "INSERT INTO users (username, email, age) VALUES (:username, :email, :age)",
  175. $insertData
  176. );
  177. if ($result) {
  178. echo "插入成功,新记录ID: " . $result['lastInsertId'] . "\n";
  179. }
  180. // 示例2: 查询数据
  181. $users = $dbOps->safeQuery(
  182. "SELECT * FROM users WHERE age > :min_age",
  183. ['min_age' => 20]
  184. );
  185. if ($users !== false) {
  186. echo "查询到 " . count($users) . " 条记录\n";
  187. foreach ($users as $user) {
  188. echo "ID: {$user['id']}, 用户名: {$user['username']}, 邮箱: {$user['email']}\n";
  189. }
  190. // 示例3: 更新数据
  191. $updateResult = $dbOps->safeExecute(
  192. "UPDATE users SET age = :new_age WHERE username = :username",
  193. ['new_age' => 26, 'username' => 'john_doe']
  194. );
  195. if ($updateResult) {
  196. echo "更新了 " . $updateResult['changes'] . " 条记录\n";
  197. // 示例4: 删除数据
  198. $deleteResult = $dbOps->safeExecute(
  199. "DELETE FROM users WHERE username = :username",
  200. ['username' => 'test_user']
  201. );
  202. if ($deleteResult) {
  203. echo "删除了 " . $deleteResult['changes'] . " 条记录\n";
  204. // 示例5: 批量插入
  205. $batchData = [
  206. ['username' => 'user1', 'email' => 'user1@example.com', 'age' => 30],
  207. ['username' => 'user2', 'email' => 'user2@example.com', 'age' => 28],
  208. ['username' => 'user3', 'email' => 'user3@example.com', 'age' => 35]
  209. ];
  210. $batchResult = $dbOps->batchInsert('users', $batchData);
  211. if ($batchResult !== false) {
  212. echo "批量插入了 {$batchResult} 条记录\n";
  213. }
  214. // 关闭连接
  215. $dbOps->close();
  216. } catch (Exception $e) {
  217. echo "错误: " . $e->getMessage() . "\n";
  218. }
  219. // 错误处理示例
  220. try {
  221. $dbOps = new SQLite3SafeOperations('test.db');
  222. // 故意制造错误 - 重复插入相同用户名
  223. $result = $dbOps->safeExecute(
  224. "INSERT INTO users (username, email, age) VALUES (:username, :email, :age)",
  225. ['username' => 'john_doe', 'email' => 'duplicate@example.com', 'age' => 40]
  226. );
  227. if ($result === false) {
  228. echo "操作失败,错误信息: " . $dbOps->getError() . "\n";
  229. }
  230. $dbOps->close();
  231. } catch (Exception $e) {
  232. echo "错误: " . $e->getMessage() . "\n";

屏幕截图 2025-12-01 202604



欢迎访问源界面 从代码出发,向无限可能延伸.
【 可以发现更多的个人博客站点,点点滴滴,网络空间中的站点生活! 】

生活看更多

  • © 2025 看分享 阅见世界,分享此刻。
  • 建议
  • | 鄂ICP备14016484号-7

    鄂公网安备 42068402000189

    访问微博看分享