sqlite3增删查改

/打开数据库,不存在则创建/

QString DBpath = QCoreApplication::applicationDirPath() + "/text.db";
int pRet = sqlite3_open(DBpath.toUtf8().data(), &g_pDb);//succeed return 0

/创建一个名叫hello的表格,写入数据*****/**

g_dbMutex.lock();
if (0 == sqlite3_exec(g_pDb, "create table hello (id int primary key ,name varchar(512),core int)", NULL, NULL, NULL))
{
	QByteArray sql = QString("insert into hello values(1,'%1',100)").arg(QObject::tr("libai")).toUtf8();//增
	sqlite3_exec(g_pDb, sql.data(), NULL, NULL, NULL);//执行字符串代码
}

g_dbMutex.unlock();

	pSql = QString("SELECT * FROM hello ").toUtf8();
	
	g_dbMutex.lock();
	
	int pRet = sqlite3_get_table(g_pDb, pSql.data(), &pazResult, &pnRow, &pnColumn, &errMsg);
	/*0,1,2,,,,,,,n-1*这一列是标题不可识别/
	/*n ,,,,,,,,,,2n*///所以从下表为n开始读取,n为列数,也叫字段数

	g_dbMutex.unlock();
	int  id;
	QString name;
	int core;
	QString ret;
	QString m_ret;
	ui.textEdit_2->clear();
	for (int i = 1; i < pnRow + 1; i++)
	{
	  id = QString(pazResult[i*pnColumn]).toInt();
	  name = QString::fromUtf8(pazResult[i*pnColumn + 1]);
	  core = QString(pazResult[i*pnColumn+2]).toInt();
	  ret = QString("name:%1 id:%2 core:%3 \n").arg(name).arg(id).arg(core);
	  m_ret += ret;
	  m_sqlnamel.append(name);

	  QStandardItem* m_itemname = new QStandardItem(name);
	  QStandardItem* m_itemid = new QStandardItem(QString::number(id));
	  QStandardItem* m_itemcore = new QStandardItem(QString::number(core));

	  QList items;
	  items.append(m_itemname);
	  items.append(m_itemid);
	  items.append(m_itemcore);

	  m_QStandardItemModel->appendRow(items); 
	}
	sqlite3_free_table(pazResult);

g_dbMutex.lock();
QByteArray sql = QString("delete from hello where name =('%1')").arg(m_name).toUtf8();//删
int ret = sqlite3_exec(g_pDb, sql.data(), NULL, NULL, NULL);//执行字符串代码
g_dbMutex.unlock();

g_dbMutex.lock();

//sqlite3_stmt* ppStmt;
//int pRet = sqlite3_prepare_v2(g_pDb, "update hello set id =? ,core=? WHERE name =?",sizeof("update hello set id=? , core=? WHERE name=?"), &ppStmt, NULL);
准备一个空句柄ppStmt(逗号分隔需要改变的值,符号需要是英文格式)
//
//int r1 = sqlite3_bind_int(ppStmt, 1,id);//给改句柄第二个参数赋值
//int r2 =  sqlite3_bind_int(ppStmt, 2, core);//给改句柄第二个参数赋值
//int r3 =  sqlite3_bind_text(ppStmt, 3, m_name.toUtf8().data(), strlen(m_name.toUtf8().data()), NULL);//给改句柄第一个参数赋值
//pRet = sqlite3_step(ppStmt);//执行句柄
//pRet = sqlite3_finalize(ppStmt);//结束句柄
//g_dbMutex.unlock();
QByteArray sql = QString("update hello set id =%1,core=%2 WHERE name =('%3')").arg(id).arg(core).arg(m_name).toUtf8();//字符串需要加单引号才可以成功
int pRet = sqlite3_exec(g_pDb, sql.data(), NULL, NULL, NULL);
g_dbMutex.unlock();

你可能感兴趣的:(sqlite3)