int InsertNewMsgAndReturnID(LPCTSTR title,LPCTSTR time,int status,int audioFrames,int audioTime,int videoFrames,int videoTime,int startAudioTime,int startVideoTime)
{
//判断是否超过10条数据,如果超过,则删除一条
CppSQLite3DB db;
int ID;
try
{
//打开数据库
db.open(LEAVE_MSG_DATABASE_FILE);
//判断是否打开成功
if(!db.mpDB)
{
// 打开失败,判断数据库文件是否存在,不存在则创建
if(CreateDatabase())
{
// 再次打开
db.open(LEAVE_MSG_DATABASE_FILE);
// 打开失败
if(!db.mpDB)
{
throw 0;
}
}else
{
throw 0;
}
}
//表不存在,新建表
if(!db.tableExists(L"Message"))
{
//建立表格
db.execDML(L"create table Message(ID int, title char(50),time char(50),status int,audioFrames int,audioTime int,videoFrames int,videoTime int,startAudioTime int,startVideoTime int);");
}
//查询数据
CppSQLite3Query q = db.execQuery(L"select COUNT(*) from Message;");
if(!q.eof())
{
int count = q.getIntField(0);
if(count >= 10)
{
//需要删除一条,首先查找最旧的已读的留言
int deleteID = 0;
q = db.execQuery(L"select MIN(ID) from Message WHERE status = 1 ;");
if(!q.eof())
{
deleteID = q.getIntField(0);
}else
{
q = db.execQuery(L"select MIN(ID) from Message;");
if(!q.eof())
{
deleteID = q.getIntField(0);
}
}
//如果找到,删除之
if(deleteID)
{
CString delSql = L"DELETE FROM Message WHERE ID = ";
CString appendSql;
appendSql.Format(L"%d",deleteID);
delSql += appendSql;
db.execDML(delSql);
//删除对应的音视频文件
CString delFile = AUDIO_FILE_PATH;
appendSql.Format(L"%d.wave",deleteID);
delFile += appendSql;
DeleteFile(delFile);
delFile = VIDEO_FILE_PATH;
appendSql.Format(L"%d.yuv",deleteID);
delFile += appendSql;
DeleteFile(delFile);
}
}
}
//获取最大的ID
int maxID = 0;
q = db.execQuery(L"select MAX(ID) from Message;");
if(!q.eof())
{
maxID = q.getIntField(0);
}
//插入新的记录
CString insertSql = L"insert into Message values(";
CString appendSql;
appendSql.Format(L"%d,",maxID+1);
insertSql += appendSql;
appendSql.Format(L"'%s',",title);
insertSql += appendSql;
appendSql.Format(L"'%s',",time);
insertSql += appendSql;
appendSql.Format(L"%d,",status);
insertSql += appendSql;
appendSql.Format(L"%d,",audioFrames);
insertSql += appendSql;
appendSql.Format(L"%d,",audioTime);
insertSql += appendSql;
appendSql.Format(L"%d,",videoFrames);
insertSql += appendSql;
appendSql.Format(L"%d,",videoTime);
insertSql += appendSql;
appendSql.Format(L"%d,",startAudioTime);
insertSql += appendSql;
appendSql.Format(L"%d",startVideoTime);
insertSql += appendSql;
appendSql.Format(L"%s",")");
insertSql += appendSql;
db.execDML(insertSql);
ID = maxID+1 ;
}catch(...)
{
ID = 0;
}
//关闭数据库
db.close();
return ID;
}
增删改查全在里面了