#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<iostream>
#include<string>
#include<QtSql/QSqlDatabase>
#include<QDebug>
//QT += sql;
using namespace std;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
//显示驱动
qDebug()<<"available drivers:";
QStringList drivers = QSqlDatabase::drivers();
foreach(QString driver, drivers)
qDebug()<<driver;
//打开MySQL
QSqlDatabase data_base = QSqlDatabase::addDatabase("QMYSQL","2");
data_base.setHostName("127.0.0.1"); //设置主机地址
data_base.setPort(3309); //设置端口
data_base.setDatabaseName("mysql"); //设置数据库名称
data_base.setUserName("root"); //设置用户名
data_base.setPassword(""); //设置密码
if(!data_base.open())
qDebug()<<"failed to connect to mysql";
else
qDebug()<<"success";
}