用的是网上别人发的测试连通性的代码
mysqtest.pro
#-------------------------------------------------
#
# Project created by QtCreator 2011-10-24T17:15:14
#
#-------------------------------------------------
QT += core gui
QT += sql
TARGET = mysqltest
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QtSql>
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QMessageBox>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase *db = new QSqlDatabase(QSqlDatabase::addDatabase("QMYSQL"));
db->setHostName("192.168.1.133");
db->setDatabaseName("hello");
db->setUserName("root");
db->setPassword("root");
if(!db->open())
{
qDebug()<<"not open";
QMessageBox::information(NULL,"show","not open!");
return 0;
}
else
{
qDebug()<<"open seccess";
QMessageBox::information(NULL,"show","open seccess!");
}
QSqlQuery queryBill;
queryBill.exec("select * from bills");
while(queryBill.next())
{
qDebug()<<"get test="<<queryBill.value(queryBill.record().indexOf("TEST")).toString();
}
QString DBname = db->connectionName();
//db->close();
if(db!=NULL)
{
delete db;
db=NULL;
}
QSqlDatabase::removeDatabase(DBname);
// MainWindow w;
// w.show();
return a.exec();
}
mainwindow.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}