• SQLite3使用笔记(2)——插入


    1. 论述

    如同上一篇文章SQLite3使用笔记(1)——查询所述,使用SQLite进行查询操作同样有两种方式。对于比较简单的表格插入,使用sqlite3_exec()接口就可以了:

      string strSql = "";
      strSql += "insert into user(name,age)";
      strSql += "values('";
      strSql += sName;
      strSql += "',";
      strSql += sAge;
      strSql += ");";
    
      char* cErrMsg;
      int nRes = sqlite3_exec(pDB, strSql.c_str(), 0, 0, &cErrMsg);
      if (nRes != SQLITE_OK) {
        cout << "add user fail: " << cErrMsg << endl;
        return false;
      } else {
        cout << "add user success: " << sName.c_str() << "\t" << sAge.c_str()
             << endl;
      }
    
      sqlite3_free(cErrMsg);
    

    但是对于一些比较复杂的情况,比如插入一个BLOB类型的数据,更加推荐使用编译statement,然后传递参数的办法:

    	sqlite3_stmt *stmt = nullptr;
    
    	char sqlStr[256] = { 0 };
    	sprintf(sqlStr, "insert into tiles(zoom_level, tile_column, tile_row, tile_data) "
    		"values(%d, %d, %d, ?)", zi, xi, yi);
    
    	int rc = sqlite3_prepare_v2(pDB, sqlStr, -1, &stmt, NULL);
    	if (rc != SQLITE_OK) 
    	{
    		cerr << "prepare failed: " << sqlite3_errmsg(pDB) << endl;
    		return;
    	}
    	else 
    	{
    		// SQLITE_STATIC because the statement is finalized
    		// before the buffer is freed:
    		rc = sqlite3_bind_blob(stmt, 1, buffer, size, SQLITE_STATIC);
    		if (rc != SQLITE_OK) 
    		{
    			cerr << "bind failed: " << sqlite3_errmsg(pDB) << endl;
    		}
    		else 
    		{
    			rc = sqlite3_step(stmt);
    			if (rc != SQLITE_DONE)
    			{
    				cerr << "execution failed: " << sqlite3_errmsg(pDB) << endl;
    			}				
    		}
    	}
    
    	sqlite3_finalize(stmt); 
    

    sqlite3_prepare_v2()编译的sql语句中的?代表一个参数,通过sqlite3_bind_blob()进行绑定。sqlite3_bind_X也是一系列的函数,blob表示绑定的是一个二进制流,这个二进制buffer最终通过执行sqlite3_step()后插入到数据库中。由于插入操作只有一次,所以第一次就会返回SQLITE_DONE,不用像查询操作那样迭代遍历。

    2. 总结

    无论查询和插入,都可以使用sqlite3_exec()这样的简易接口,或者使用编译statement然后执行两种方式。个人感觉非常像JDBC中Statement和Preparement,一种是直接拼接执行,一种是预编译后传参执行。当然更加推荐使用编译后执行传参的方式,效率高,控制度更细一点,能预防SQL注入。

  • 相关阅读:
    第三篇:python函数
    第二篇:数据类型
    第一篇:初识python
    PyTorch教程之Autograd
    PyTorch教程之Tensors
    如何解决Python.h:No such file or directory
    如何解决conda install:command not found问题
    Linux 安装Anaconda 4.4.0
    Linux安装pytorch的具体过程以及其中出现问题的解决办法
    Writing Science 7.10 (The Opening and The Funnel)
  • 原文地址:https://www.cnblogs.com/charlee44/p/16298965.html
Copyright © 2020-2023  润新知