• C++ 使用SQLite


    1.SQLite是一个完全独立的、不需要服务器、不要任何配置、支持SQL的、开源的文件数据库引擎。源代码和支持可以登录:http://www.sqlite.org/ 
      1.1.下载sqlite3.dll和sqlite3.def文件,在下载页下载sqlite-dll-win32-x86-3080803文件

      1.2.下载sqlite3.h,在下载页下载sqlite-amalgamation-201503091040文件。

    2.代码编译,由于SQLite下载文件中只提供了def文件而没有提供lib文件。所以在正式使用sqlite之前需要先编译lib文件。下面给出编译lib文件的方法和步骤。

      2.1 打开VS自带的命令行工具。

      2.2在上面的命令行中输入(注意空格):(小技巧,输入lib.exe  /def:后可以将刚刚解压sqlite3.def直接拖到命令行界面中,然后加上/machine:ix86)

        D:Program FilesMicrosoft Visual Studio 10.0VC>lib.exe /def:F:TDdownloadsqlite-dll-win32-x86-3080803sqlite3.def /machine:ix86

      回车编译完成。

     2.3 编译完成后生成sqlite3.lib、sqlite3.exp文件,该文件路径在:C:Program FilesMicrosoft Visual Studio 9.0VC

    参考 http://blog.sina.com.cn/s/blog_a459dcf501013pwv.html

     把sqlite3.h拷贝到代码目录下,sqlite3.lib,sqlite3.dll文件拷贝到生成exe目录下。

    #include <windows.h>   

    #include "..SQLitesqlite3.h"    

    #pragma comment(lib,"sqlite3.lib")   

     

    sqlite3 * pDB = NULL;
    int SQLiteDB::OpenDB()
    {
        CMyFile myfile;
        CMyString mystring;
        string s_db_path = myfile.GetRunDir() + "\TS15.db";
    
        char *c_db_path = new char[s_db_path.length() + 1];
        strcpy(c_db_path, s_db_path.c_str());
    
    
        int ret = sqlite3_open(c_db_path, &pDB);
        if (ret != SQLITE_OK)
        {
            sqlite3_close(pDB);
            return 2;
        }
    
        //delete[]c_db_path;
        //return ret;
        return ret;
    }
    
    int SQLiteDB::ExecuteSql(string sql)
    {
            char *c_sql = new char[sql.length() + 1];        
            strcpy_s(c_sql, strlen(c_sql), sql.c_str());
            char* c_err_msg;
    
            int  ret = sqlite3_exec(pDB, c_sql, 0, 0, &c_err_msg);
            
    
            if (ret != SQLITE_OK)
            {
                //cout << "select fail: " << cErrMsg << endl;
                sqlite3_close(pDB);
                return 3;
            }
            
            return 0;
    
    }
    
    int SQLiteDB::CloseSQLiteDB()
    {
    
        sqlite3_close(pDB);
        return 0;
    }

     

    // ConvertPrintVarDlg.cpp : implementation file
    //
    
    #include "stdafx.h"
    #include "ConvertPrintVar.h"
    #include "ConvertPrintVarDlg.h"
    #include "afxdialogex.h"
    
    #ifdef _DEBUG
    #define new DEBUG_NEW
    #endif
    
    
    // CAboutDlg dialog used for App About
    
    class CAboutDlg : public CDialogEx
    {
    public:
        CAboutDlg();
    
    // Dialog Data
        enum { IDD = IDD_ABOUTBOX };
    
        protected:
        virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
    
    // Implementation
    protected:
        DECLARE_MESSAGE_MAP()
    };
    
    CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
    {
    }
    
    void CAboutDlg::DoDataExchange(CDataExchange* pDX)
    {
        CDialogEx::DoDataExchange(pDX);
    }
    
    BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
    END_MESSAGE_MAP()
    
    
    // CConvertPrintVarDlg dialog
    
    
    
    CConvertPrintVarDlg::CConvertPrintVarDlg(CWnd* pParent /*=NULL*/)
        : CDialogEx(CConvertPrintVarDlg::IDD, pParent)
    {
        m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
    }
    
    void CConvertPrintVarDlg::DoDataExchange(CDataExchange* pDX)
    {
        CDialogEx::DoDataExchange(pDX);
    }
    
    BEGIN_MESSAGE_MAP(CConvertPrintVarDlg, CDialogEx)
        ON_WM_SYSCOMMAND()
        ON_WM_PAINT()
        ON_WM_QUERYDRAGICON()
        ON_BN_CLICKED(IDC_BUTTON_OK, &CConvertPrintVarDlg::OnBnClickedButtonOk)
    END_MESSAGE_MAP()
    
    
    // CConvertPrintVarDlg message handlers
    
    BOOL CConvertPrintVarDlg::OnInitDialog()
    {
        CDialogEx::OnInitDialog();
        GetDlgItem(IDC_STATIC_MSG)->SetWindowText(_T(""));
        // Add "About..." menu item to system menu.
    
        // IDM_ABOUTBOX must be in the system command range.
        ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
        ASSERT(IDM_ABOUTBOX < 0xF000);
    
        CMenu* pSysMenu = GetSystemMenu(FALSE);
        if (pSysMenu != NULL)
        {
            BOOL bNameValid;
            CString strAboutMenu;
            bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
            ASSERT(bNameValid);
            if (!strAboutMenu.IsEmpty())
            {
                pSysMenu->AppendMenu(MF_SEPARATOR);
                pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
            }
        }
    
        // Set the icon for this dialog.  The framework does this automatically
        //  when the application's main window is not a dialog
        SetIcon(m_hIcon, TRUE);            // Set big icon
        SetIcon(m_hIcon, FALSE);        // Set small icon
    
        // TODO: Add extra initialization here
    
        return TRUE;  // return TRUE  unless you set the focus to a control
    }
    
    void CConvertPrintVarDlg::OnSysCommand(UINT nID, LPARAM lParam)
    {
        if ((nID & 0xFFF0) == IDM_ABOUTBOX)
        {
            CAboutDlg dlgAbout;
            dlgAbout.DoModal();
        }
        else
        {
            CDialogEx::OnSysCommand(nID, lParam);
        }
    }
    
    // If you add a minimize button to your dialog, you will need the code below
    //  to draw the icon.  For MFC applications using the document/view model,
    //  this is automatically done for you by the framework.
    
    void CConvertPrintVarDlg::OnPaint()
    {
        if (IsIconic())
        {
            CPaintDC dc(this); // device context for painting
    
            SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
    
            // Center icon in client rectangle
            int cxIcon = GetSystemMetrics(SM_CXICON);
            int cyIcon = GetSystemMetrics(SM_CYICON);
            CRect rect;
            GetClientRect(&rect);
            int x = (rect.Width() - cxIcon + 1) / 2;
            int y = (rect.Height() - cyIcon + 1) / 2;
    
            // Draw the icon
            dc.DrawIcon(x, y, m_hIcon);
        }
        else
        {
            CDialogEx::OnPaint();
        }
    }
    
    // The system calls this function to obtain the cursor to display while the user drags
    //  the minimized window.
    HCURSOR CConvertPrintVarDlg::OnQueryDragIcon()
    {
        return static_cast<HCURSOR>(m_hIcon);
    }
    
    
    sqlite3 * pDB = NULL;
    
    string save_file_path;
    
    bool WritePrintData();
    void ReadPrintData(string file_path);
    bool AddPrintData(string var_name, string var1);
    bool UpdatePrintData(string var_name, string var2, string var3, string var4);
    bool DeletePrintData();
    int Sqlite3ExecCallback(void *data, int nColumn,char **colValues, char **colNames);
    
    void CConvertPrintVarDlg::OnBnClickedButtonOk()
    {
        // TODO: Add your control notification handler code here
        GetDlgItem(IDC_STATIC_MSG)->SetWindowText(_T(""));
        CString  file_path;
        GetDlgItemTextW(IDC_MFCEDITBROWSE_File, file_path);
        if (file_path == "")
        {
            GetDlgItem(IDC_STATIC_MSG)->SetWindowText(_T("please select file path"));
            return;
        }
        CMyFile myfile;
        CMyString mystring;
    
        string run_dir=myfile.GetRunDir();
        string db_path = run_dir + "\db.db";
        char* c_db_path = mystring.StringToPchar(db_path);
        //IDC_MFCEDITBROWSE_File
    
    
        int find_index = file_path.ReverseFind('\');
    
        CString  file_current_path = file_path.Mid(0, find_index);
        
        CString  cs_save_file_path = file_current_path + "\printvar.txt";
    
        DeleteFile(cs_save_file_path);
    
        int len = WideCharToMultiByte(CP_ACP, 0, cs_save_file_path, -1, NULL, 0, NULL, NULL);
        char *ptxtTemp = new char[len + 1];
        WideCharToMultiByte(CP_ACP, 0, cs_save_file_path, -1, ptxtTemp, len, NULL, NULL);
    
    
        save_file_path = ptxtTemp;
        
        int nRes = sqlite3_open(c_db_path, &pDB);
    
       if (nRes != SQLITE_OK)
       {
         /*  cout << "Open database fail: " << sqlite3_errmsg(pDB);
           goto QUIT;*/
           GetDlgItem(IDC_STATIC_MSG)->SetWindowText(_T("database fail"));
       }
       else
       {
           DeletePrintData();
           ReadPrintData("E:\ProgramTest\ConvertPrintVar\Debug\1.cpp");
    
           WritePrintData();
    
           GetDlgItem(IDC_STATIC_MSG)->SetWindowText(_T("ok"));
       }
     
    }
    
    string& trim(string &s)
    {
        if (s.empty())
        {
            return s;
        }
    
        s.erase(0, s.find_first_not_of(" "));
        s.erase(s.find_last_not_of(" ") + 1);
        return s;
    }
    
    void ReadPrintData(string file_path)
    {
        
        ifstream s;
        string text_line = "";
        string line_temp = "";
    
        string var_name;
        string var1;
        string var2;
        string var3;
        string var4;
        int find_index10 = 0;
        int find_index11 = 0;
        int find_index12 = 0;
        int find_index13 = 0;
        int find_index14 = 0;
    
        int find_index00 = 0;
        int find_index20 = 0;
        int find_index21= 0;
        int find_index22 = 0;
        int find_index23 = 0;
        int find_index24 = 0;
        int find_index25 = 0;
        int find_index26 = 0;
    
        string str1;
        string str11;
        string str2;
        string str3;
        s.open(file_path, ios::in);
        if (s)
        {
            while (!s.eof())
            {
                getline(s, text_line);
    
                if (text_line != "")
                {
                
                //const  char* PrintData::PRT_DATE = QT_TR_NOOP("Date");    
                find_index10 = text_line.find("QT_TR_NOOP");        
                find_index00 = text_line.find("//");
                if (find_index10>0 && find_index00==-1)
                {
                    find_index11 = text_line.find("::");
    
                    find_index12 = text_line.find("=");
    
                    find_index13 = text_line.find_first_of('(');
                    find_index14 = text_line.find_last_of(')');
    
                    var_name = text_line.substr(find_index11+2, find_index12 - find_index11-2);
                    var1 = text_line.substr(find_index13+2, find_index14- find_index13-3);
                    trim(var_name);
                    trim(var1);
                    AddPrintData(var_name, var1);
                    
                }
                //{PrintData::PRT_NET, "10.00", 7, PrintData::RIGHT},
                find_index20 = text_line.find("{PrintData");
    
                if (find_index20 > 0 && find_index00 == -1)
                {
            
                    find_index21 = text_line.find_first_of(',');                
                    var_name = text_line.substr(find_index20 + 12, find_index21 - find_index20 - 12);
    
                    str1 = text_line.substr(find_index21+1);
                    trim(str1);
                    find_index22 = str1.find_first_of(',');
    
                    str11 = str1.substr(1, find_index22-1);
    
                    trim(str11);
                    var2 = str11.substr(0, str11.length()-1);
                    //var2 = str1.substr(1, find_index22-2);
    
                    str2 = str1.substr(find_index22+1);
    
                    trim(str2);
                    find_index23 = str2.find_first_of(',');
    
                    var3 = str2.substr(0, find_index23);
    
                    
                    str3 = str2.substr(find_index23+1);            
                    trim(str3);
    
                    find_index24 = str3.find("}");
    
                    var4 = str3.substr(11, find_index24 - 11);
                    trim(var_name);
                    trim(var2);
                    trim(var3);
                    trim(var4);
                    UpdatePrintData(var_name, var2, var3, var4);
    
                }
                text_line = "";
    
              } //end if(text_line != "")
    
            }
        }
        s.close();
    
    }
    
    bool WritePrintData()
    {
        string sql = "select Variable1,Variable2,Variable3,Variable4 from PrintData";
        char *c_sql = new char[sql.length() + 1];
        // strcpy(c_sql, sql.c_str());
        strcpy_s(c_sql, strlen(c_sql), sql.c_str());
        char* c_err_msg;
        int  ret = sqlite3_exec(pDB, c_sql,&Sqlite3ExecCallback, 0, &c_err_msg);
        if (ret != SQLITE_OK)
        {
            
            //cout << "select fail: " << cErrMsg << endl;
            return false;
        }
      return true;
        
    }
    int Sqlite3ExecCallback(void *data, int nColumn, char **colValues, char **colNames)
    {
        //for (int i = 0; i < nColumn; i++)
        //{
    
    
        //    //printf("%s	", colValues[i]);
        //}
        //printf("
    ");
        string var1 = colValues[0];
        string var2 = colValues[1];
        string var3 = colValues[2];
        string var4 = colValues[3];
        string str = var1 + ":" + var3 + ":" + var1 + ":" + var1 + ":" + var2;
        
        //添加模式
        ofstream  s(save_file_path, ios::app);
        if (!s)
        {
            s.close();
        }
        s << str<< endl;
        s.close();
    
        return 0;
    }
    
    bool AddPrintData(string var_name, string var1)
    {
        
        string sql = "insert into PrintData(VarName,Variable1,Variable2,Variable3,Variable4)values('";
        sql += var_name + "','" + var1 + "'," + "'',"+"''," + "'')";
        
        char *c_sql = new char[sql.length() + 1];
        // strcpy(c_sql, sql.c_str());
        strcpy_s(c_sql, strlen(c_sql), sql.c_str());
        char* c_err_msg;
        int  ret = sqlite3_exec(pDB, c_sql, 0, 0, &c_err_msg);
    
        //delete[] c_sql;
        //c_sql = nullptr;
    
        if (ret != SQLITE_OK)
        {
            //cout << "select fail: " << cErrMsg << endl;
            return false;
        }
        return true;
    }
    bool UpdatePrintData(string var_name, string var2, string var3, string var4)
    {
    
    
        
    string    sql = "update PrintData set Variable2='";
        sql += var2 + "', Variable3='";
        sql += var3 + "', Variable4='";
        sql += var4 +"' where VarName='";
        sql += var_name +"'";
    
        char *c_sql = new char[sql.length() + 1];
        //strcpy(c_sql, sql.c_str());
        strcpy_s(c_sql, strlen(c_sql), sql.c_str());
    
        char* c_err_msg;    
        int  ret = sqlite3_exec(pDB, c_sql, 0, 0, &c_err_msg);
        //delete[] c_sql;
        //c_sql = nullptr;
        if (ret != SQLITE_OK)
        {
            //cout << "select fail: " << cErrMsg << endl;
            return false;
        }
        return true;
    }
    bool DeletePrintData()
    {
        
        string sql = "delete from PrintData ";
        char* c_err_msg;    
        char *c_sql = new char[sql.length() + 1];
        //strcpy(c_sql, sql.c_str());
        strcpy_s(c_sql, strlen(c_sql), sql.c_str());
    
        int  ret = sqlite3_exec(pDB, c_sql, 0, 0, &c_err_msg);
    
        if (ret != SQLITE_OK)
        {
            //cout << "select fail: " << cErrMsg << endl;
            return false;
        }
    
    
    
        return true;
    
    
    
    }
  • 相关阅读:
    asy for
    asy html !
    lib
    git clone 指定 version tag
    git tag
    git clone <url>--depth 、 git clone <url> --recursive
    xelatex CLI
    rsync
    curl options
    [转自]C语言offset_of宏和container_of宏
  • 原文地址:https://www.cnblogs.com/ike_li/p/4346958.html
Copyright © 2020-2023  润新知