bool database::createDatabase()
{
QSqlQuery query // 此处请查询 query的相关 *** 作
qDebug() <<"Start to create table..."
//create table: User
query.exec("CREATE TABLE [User] ( [userId] VARCHAR(40) NOT NULL, [username] VARCHAR(40) NOT NULL, [email] VARCHAR(40), [password] VARCHAR(40), [city] VARCHAR(20), PRIMARY KEY([userId]) )")// 一定注意不要拼写错误,引号内是不提示拼写错误的。
//create table: Connect
query.exec("CREATE TABLE [Connect] ( [LeftUser] VARCHAR(40) NOT NULL, [RightUser] VARCHAR(40) NOT NULL, [relation] INTEGER DEFAULT '0' NULL, PRIMARY KEY ([LeftUser], [RightUser]))")
if (query.lastError().isValid())
{
qDebug() <<query.lastError()
return false
}
else
{
qDebug() <<"Create database successfully."
}
return true
}
插入 *** 作
bool database::adduser( User user )
{
if (!db.isOpen())
{
createconnection()
}
QSqlQuery query
qDebug() <<"start to insert data"
query.exec("INSERT INTO [User] ( userId, username, email, password, city) VALUES(?,?,?,?,?)")
QVariantList userId
userId <<user.getUserId()
query.addBindValue(userId)
QVariantList username
username <<user.getUserName()
query.addBindValue(username)
QVariantList email
email <<user.getEmail()
query.addBindValue(email)
QVariantList password
password <<user.getPassword()
query.addBindValue(password)
QVariantList city
city <<user.getCity()
query.addBindValue(city)
try
{
if (!query.execBatch())
{
qDebug() <<query.lastQuery()
qDebug() <<query.lastError()
return NULL
}
}
catch(...)
{
QMessageBox::critical(0, "Add New Node error!",
"Unable to add a new Node!/n/n"
"Click Cancel to exit.", QMessageBox::Cancel)
}
if( !UpdateConnectTable(user.getUserId(),user.getUserId(),2))
{
QMessageBox::critical(0,"","Update table Connect error")
return NULL
}
return true
}
连接mysql 数据库QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL")// 使用mysql数据库驱动
db.setHostName("localhost")
db.setDatabaseName("exampledb")// 数据库名称
db.setUserName("sa")// 用户名
db.setPassword("1")// 密码
bool ok = db.open()// 尝试连接数据库
if(ok)
{
QSqlQuery myquery
if(myquery.exec("select * from employeedb"))
{
int num = 0
if(db.driver()->hasFeature(QSqlDriver::QuerySize))
{
num = myquery.size()// 如果支持结果影响的行数,那么直接记录下来
}
else
{
myquery.last()//否则定位到结果最后
num = myquery.at() + 1
}
//这里添加数据库的查询结果处理 *** 作
}
else // 如果查询失败
{
QSqlError error = myquery.lastError()
}
}
else // 打开数据库失败
{
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)