You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

119 lines
2.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "data_base.h"
QSqlDatabase database;
void Data_base::set_database()
{
// 创建数据库命名为Pet_project.db
database = QSqlDatabase::addDatabase("QSQLITE");
database.setDatabaseName("Pet_project.db");
if (!database.open())
{
qDebug() << "Error: Failed to connect database." << database.lastError();
}
else
{
qDebug() << "Succeed to connect database." ;
}
}
void Data_base::delete_table(){
//删除表格
QSqlQuery to_user;
to_user.exec("drop table USER");
if(to_user.exec())
{
qDebug() << to_user.lastError();
}
else
{
qDebug() << "Table cleared";
}
}
void Data_base::creat_table()
{
//在数据库中新建立一个表格,用于记录用户信息
QSqlQuery to_user;
QStringList table_list = database.tables();
if(!table_list.contains("USER"))
{
//在数据库中新建立一个表格,用于记录用户信息
if(!to_user.exec("create table USER(user_name varchar primary key,password varchar)"))
{
qDebug() << "Error: Fail to create table."<< to_user.lastError();
}
else{
qDebug() << "Table user created!";
}
}
else{
qDebug()<<"USER already exist";
}
QString Username = "pet";
QString s = QString("SELECT * FROM USER where user_name='%1' ").arg(Username);
to_user.exec(s);
int num=0;
while(to_user.next())
{
num++;
}
if(num==0)
{
//给用户表中插入一个初始的用户,我的超级用户
to_user.exec("insert into USER values('pet', '123456')");
}
if(!table_list.contains("COMMUNICATION"))
{
//在数据库中新建立一个表格,用于记录用户信息
if(!to_user.exec("create table COMMUNICATION(the_content varchar,the_user varchar)"))
{
qDebug() << "Error: Fail to create Communication table."<< to_user.lastError();
}
else{
qDebug() << "Table COMMUNICATION created!";
}
}
else{
qDebug()<<"COMMUNICATION already exist";
}
}
bool Data_base::check_user(QString Username, QString Password)
{
if(database.open())
{
QSqlQuery check(database);
//查询是给返回一个满足条件的表如果没有表为空check一开始指向的是返回的表之外
QString s = QString("SELECT * FROM USER where user_name='%1' and password='%2' ").arg(Username).arg(Password);
check.exec(s);
int num=0;
while(check.next())
{
num++;
}
if(num!=0) return true;
else return false;
}
}