在网上找了很多SQLServer的封装类, 自己重新实现了一下
参考的网址:
这个是一个数据库操作的类, 包含基本的打开关闭curd
点击打开链接
这个是参考实现count, 在迭代器里增加了一个int变量用于计数
点击打开链接
Qt版本 4.8.6
1. 文档结构
2. .pro
这里要增加 Qt += sql
#-------------------------------------------------
#
# Project created by QtCreator 2018-06-12T10:23:08
#
#-------------------------------------------------
QT += core
QT -= gui
QT += sql
TARGET = SQLServerDemo
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
sqlserverhelper.cpp
HEADERS += \
sqlserverhelper.h
3. main.cpp
这里实现的功能是查询计数和插入记录
#include
#include "sqlserverhelper.h"
#include
void SQLServerTest()
{
SQLServerHelper *sqlServerHelper = new SQLServerHelper();
sqlServerHelper->open();
QString sqlCommand = "SELECT * FROM DeviceStatus WHERE DeviceCode = '001'";
int count = sqlServerHelper->count(sqlCommand);
qDebug() << count;
sqlCommand =
"INSERT INTO [dbo].[DeviceStatus]([DeviceCode], [DeviceStaTime], [DeviceStaCode], [DeviceErrCode]) VALUES ('004', '', '001', '');";
int result = sqlServerHelper->query(sqlCommand);
qDebug() << result;
sqlServerHelper->close();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
SQLServerTest();
return a.exec();
}
4. SQLServer封装类
sqlserverhelper.h
#ifndef SQLSERVERHELPER_H
#define SQLSERVERHELPER_H
#include
class SQLServerHelper
{
public:
SQLServerHelper();
QSqlDatabase sqlserver_db;
QSqlDatabase db;
void open();
void close();
int count(QString sqlCommand);
int query(QString sqlCommand);
};
#endif // SQLSERVERHELPER_H
sqlserverhelper.cpp
#include "sqlserverhelper.h"
#include
#include
SQLServerHelper::SQLServerHelper()
{
QString connectionTemplate = "DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;";
QString server = "127.0.0.1";
QString dbName = "db";
QString user = "sa";
QString password = "1";
QString connectionString = connectionTemplate.arg(server).arg(dbName);
db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName(connectionString);
db.setUserName(user);
db.setPassword(password);
}
void SQLServerHelper::open()
{
if (db.open())
{
qDebug("sqlserver connect successfully.");
}
else
{
qDebug("sqlserver connect failed.");
}
}
void SQLServerHelper::close()
{
db.commit();
db.close();
}
int SQLServerHelper::count(QString sqlCommand)
{
QSqlQuery query(db);
query.prepare(sqlCommand);
int recCount = 0;
if(query.exec())
{
while(query.next())
recCount ++;
}
return recCount;
}
int SQLServerHelper::query(QString sqlCommand)
{
QSqlQuery query(db);
query.prepare(sqlCommand);
if(query.exec())
{
qDebug() << "execute successfully.";
return 1;
}
else
{
qDebug() << "execute failed.";
return 0;
}
}
ok. 这样就可以实现简单的功能了, 以后添加再更新..... 2018/06/12