1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
#!/usr/bin/env python
import sys
from qt import *
from qtsql import *
from frmconnect import frmConnect
from dbpar import *
TRUE = 1
FALSE = 0
def createConnection():
driver = DB_DRIVER
# all qt examples use QSqlDatabase::addDatabase, but
# this never returns NULL in my experience
drivers = map(str, QSqlDatabase.drivers())
if driver in drivers:
dlg = dbConnect(driver)
#TODO: make connection parameters accessible
return dlg.exec_loop()
else:
QMessageBox.warning(None, "Database Error",
"<%s> database driver not found!\n\n"
"Please make sure, that this database adaptor\n"
"is available in your Qt installation.\n" %
(driver), QMessageBox.Abort | QMessageBox.Escape)
return FALSE
class dbConnect(frmConnect):
def __init__(self, driver, parent = None):
frmConnect.__init__(self, parent)
self.hostnames = DB_HOSTNAMES
self.hostname = DB_HOSTNAMES[0]
self.databases = DB_DATABASES
self.database = DB_DATABASES[0]
self.username = DB_USERNAME
self.password = DB_PASSWORD
self.dbdriver = driver
self.txtName.setText(self.username)
self.txtPasswd.setText(self.password)
map(self.cmbServer.insertItem, self.hostnames)
map(self.cmbDatabase.insertItem, self.databases)
self.connect(self.buttonHelp, SIGNAL("clicked()"),
self.buttonHelp_clicked)
def accept(self):
self.hostname = self.cmbServer.currentText()
self.database = self.cmbDatabase.currentText()
self.username = self.txtName.text()
self.password = self.txtPasswd.text()
db = QSqlDatabase.addDatabase(self.dbdriver)
if db:
db.setHostName(self.hostname)
db.setDatabaseName(self.database)
db.setUserName(self.username)
db.setPassword(self.password)
if db.open():
frmConnect.accept(self)
else:
QMessageBox.warning(self, "Database Error",
"Cannot open %s database on %s!\n\n%s\n%s\n" %
(self.database, self.hostname,
db.lastError().driverText(),
db.lastError().databaseText()), " Ooops ")
def buttonHelp_clicked(self):
QMessageBox.information(self, "About Connecting",
"Here you specify userid, password, host and database\n"
"for the PyQt sql examples. If you encounter any problems,\n"
"please read the README file in this folder before posting.\n\n"
"Thanks,\nHans-Peter Jansen <hpj@urpla.net>\n")
if __name__ == "__main__":
app = QApplication(sys.argv)
if createConnection():
print "ok"
else:
print "cancel"
|