ubuntu linux USES Qt to connect to the MySQL database

  • 2020-05-12 06:17:55
  • OfStack

Environmental description:
ubuntu 10.04.2
QtSDK (1.5G the one that installs the package)
mysql5.1
1. Install MySQL
Full MySQL development under Linux requires the installation of the server side, and it's fine if you install the client side. Search mysql directly in the software center and select client and server.
When installing server, you will be prompted to set a password for the root user.
I used version mysql 5.1, where the username and password are stored in a database called mysql and are only visible at the administrator level.
If you enter mysql directly into the terminal, you may be prompted with ERROR 1045 (28000) because you are accessing the database under your own username, and currently there is only one root user in the database. It doesn't matter, if necessary, you can add 1 user:
mysql -uroot -p -- > Log in as root user
grant usage on *.* to dummy@localhost; -- > Authorize a user named dummy to log in locally, and change it to your own user name
However, at this time, direct mysql only has ordinary permission, so it is not allowed to create a database or operate mysql. If you really need to give it to the administrator, you can consult relevant information by yourself.
2. Install MySQL driver for Qt.
Method 1: directly sudo apt-get install libqt4-sql-mysql, which is the mysql driver for Qt4. You don't have to compile it yourself, but you might download something extra.
Will/usr/lib/qt4 plugins/sqldrivers/libqsqlmysql so copy to your QtSDK sqldrivers directory, I was directly using ordinary permissions to install, directory is: ~ / QtSDK Desktop/Qt / 473 / gcc/plugins/sqldrivers
Method 2: actually, you can also sudo apt-get download libqt4-sql-mysql, unzip the package, and copy the so files inside.
Method 3: compile as you like, but it doesn't seem to be feasible, because the new version of QtSDK doesn't have the src directory, and it doesn't have the mysql driver by default.
3. Try demo for 1 time
Remember to add QT += there in the pro file, otherwise qmake will not look for the relevant part of sql
 
#include <QtCore/QCoreApplication> 
#include <QSqlDatabase> 
#include <QDebug> 
int main(int argc, char *argv[]) 
{ 
QCoreApplication a(argc, argv); 
QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL"); 
db.setHostName("localhost"); 
db.setDatabaseName("study"); 
db.setUserName("root"); 
db.setPassword("tyh"); 
if(!db.open()){ 
qDebug()<<"Unable to open database"; 
}else{ 
qDebug()<<"Database connection established"; 
} 
return a.exec(); 
} 

I have already created study database here, and if the connection is successful, Database connection established will be displayed. I am building a console program.

Related articles: