初始化sqlite3 (创建表)
QString url = QDir::currentPath() + QString::fromLocal8Bit("/Msg.db"); bool isExsiting = false; QFileInfo file(url); if (!file.absoluteDir().exists()) { QDir dir; dir.mkpath(file.path()); } if (file.exists()) isExsiting = true; if(sqlITE_OK != sqlite3_open(url.toStdString().c_str(),&m_conn)) { sqlite3_close(m_conn); } if (!isExsiting) { char *zErrMsg= 0; char *sql= "CREATE TABLE [netmsg](\n [currentuser] [VARCHAR(50)],\n [msgType] int,\n [peername] [VARCHAR(40)],\n [peerNickname] [VARCHAR(40)],\n [msg] TEXT,\n [other_info] TEXT,[group_name] [VARCHAR(40)],\n [send_timestamp] TEXT,\n [bExtract] int);"; sqlite3_exec(m_conn,sql,&zErrMsg); }
插入数据:
sprintf_s(sql,1024,"INSERT INTO [netmsg] VALUES('%s','%d','%s','%d');",m_user_name.c_str(),msg.msgType,msg.peername.c_str(),msg.peerNickname.c_str(),msg.msg.c_str(),msg.other_info.c_str(),msg.group_name.c_str(),msg.send_timestamp.c_str(),flag); m_rc = sqlite3_prepare_v2(m_conn,strlen(sql),&m_stmt,0); if(m_rc != sqlITE_OK) { return; } sqlite3_step(m_stmt); sqlite3_finalize(m_stmt);
读取数据:
char sql[1024]; sprintf_s(sql,"SELECT * FROM [netmsg] WHERE [peername] == '%s' and [msgType] == '%d';",peerName.c_str(),PUSH_USER_CHAT_MESSAGE_); m_rc = sqlite3_prepare_v2(m_conn,0); if(m_rc) { return; } while(sqlite3_step(m_stmt) == sqlITE_ROW) { ComingMsg msg; msg.msgType = sqlite3_column_int(m_stmt,1); msg.peername = (char*)sqlite3_column_text(m_stmt,2); msg.peerNickname = (char*)sqlite3_column_text(m_stmt,3); msg.msg = (char*)sqlite3_column_text(m_stmt,4); msg.other_info = (char*)sqlite3_column_text(m_stmt,5); msg.send_timestamp = (char*)sqlite3_column_text(m_stmt,7); if ( sqlite3_column_int(m_stmt,8) == 0) { msg.bExtract = false; } else { msg.bExtract = true; } msgVec.push_back(msg); } sqlite3_finalize(m_stmt);
删除数据:
sprintf_s(sql,"DELETE FROM [netmsg] WHERE [peername] == '%s' and [msgType] == '%d';",PUSH_USER_CHAT_MESSAGE_); m_rc = sqlite3_prepare_v2(m_conn,0); if(m_rc != sqlITE_OK) { return; } sqlite3_step(m_stmt); sqlite3_finalize(m_stmt);
sqlite3第一次用,简单地把自己的使用过程写一下,以后再用到可以参考。
sqlite3对很多通过的sql语句都支持,像SELECT,UPDATE,INSERT,DELETE等等都支持地很好,只要懂sql语句就可以用sqlite3。
By 冬狼无敌 转载请注明出处:http://www.jb51.cc/article/p-wnvynbej-yv.html