Home > database >  Pyqt5 how to connect to SQL server???
Pyqt5 how to connect to SQL server???

Time:10-19

 import sys 
The from PyQt5. QtCore import *
The from PyQt5. QtGui import *
The from PyQt5. QtWidgets import *
The from PyQt5. QtSql import QSqlDatabase, QSqlQuery

Def createDB () :
# connect to the database
Db=QSqlDatabase. AddDatabase (' QODBC ')
Db. SetHostName (" LAPTOP - LEGP9GUD ")
Db. SetUserName (" BTS ")
The setPassword (" 123456 ")
Db. SetDatabaseName (" Test2 ")

If not the db. The open () :
QMessageBox. Critical (None, (" unable to open the database "), (" unable to establish a connection to the database \ n \ n click the Cancel button to exit the application of "), QMessageBox. Cancel)
Return False

Query=QSqlQuery ()
Query. Exec_ (" create table member (no int primary key, name varchar (20), unit varchar (30)) ")
Query. Exec_ (" insert into member values (4, 'the RM', 'BTS') ")
Query. Exec_ (" insert into member values (1, 'Jin', 'BTS') ")
Query. Exec_ (" insert into member values (2, 'SUGA', 'BTS') ")
Query. Exec_ (" insert into member values (3, 'J - Hope', 'BTS') ")
Query. Exec_ (" insert into member values (5, 'Jimin', 'BTS') ")
Query. Exec_ (" insert into member values (6, 'V', 'BTS') ")
Query. Exec_ (" insert into member values (7, 'JungKook', 'BTS') ")
# close the database
The close ()
Return True

If __name__=="__main__ ':
App=QApplication (sys. Argv)
CreateDB ()
Sys. Exit (app. Exec_ ())


Code as above, is not a day, now the login name and password can be normal to connect to the native database server, don't know where there is a problem, just began to learn a hope for bosses guide
  • Related