static bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", "dbTemp");
db.setHostName("FB69FCAAFBED45D"); //IP地址 或 SQL SERVER,
QString dsn = QString::fromLocal8Bit
("DRIVER={SQL SERVER};SERVER=FB69FCAAFBED45D;DATABASE=nan;");//uid=nan;pwd=123456 用windows身份认证时不用用户名密码
db.setDatabaseName(dsn);
//db.setUserName("nan"); //使用SQL server登录时用
//db.setPassword("123456");
if (!db.open())
{
QMessageBox::critical(0, qApp->tr("Cannot open database"),
qApp->tr("Unable to establish a database connection."
), QMessageBox::Cancel);
return false;
}
QSqlQuery query(db); //这里要加db
if (!query.prepare("select * from nan"))
{
QMessageBox::critical(0, qApp->tr("database "),
qApp->tr("OK"), QMessageBox::Cancel);
return false;
}
query.exec("insert into nan values(111, 'fuck you')"); //测试能否访问数据库
return true;
}
=============================================================
//增加QT对中文的支持否则识别不了数据库中文名界面中文会乱码
QTextCodec::setCodecForTr(QTextCodec::codecForName("GB2312"));QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB