PYTHON+PYQT Database Basic Operations

Source: Internet
Author: User

Sqlite:

Using Python's sqlite3:

Note that the commit method is slightly different from QT

ImportSqlite3classDBManager ():def __init__(self): self.db= Sqlite3.connect ("core.db") Self.query=self.db.cursor () ... self._inittable ( ) ...## Create table["Webpower"] if not exists    def_inittable (self): Self.query.execute ("CREATE table if not exists webpower (ID integer primary key,name text,state integer)") Self.db.commit () ...

Using Qtsql:

1  fromPyqt4.qtsqlImportQsqlquery,qsqldatabase2 3 classDBManager ():4     def __init__(self):5Self.db = Qsqldatabase.adddatabase ("Qsqlite")#Select database Type6Self.db.setDatabaseName ("core.db")#Set database name7Self.db.open ()#connect to or CREATE database8Self.query = Qsqlquery ()#SQL Handler9         ...    Ten      One...

Mysql:

 fromPyqt4.qtsqlImportQsqlquery,qsqldatabaseclassDBManager ():def __init__(self): self.db= Qsqldatabase.adddatabase ("Qmysql")#Select database TypeSelf.db.setHostName ("localhost")#Set AddressSelf.db.setUserName ("Root");#Set user nameSelf.db.setPassword ("Root");#Set user pwdSelf._trytoconnect ()#Check ConnectionSelf.query =qsqlquery ()## CREATE DATABASESELF.QUERY.EXEC_ ("CREATE DATABASE test1")        ## Choose DatabaseSelf.db.setDatabaseName ("test1") Self._trytoconnect ()#also can be:self.query.exec_ ("Use Test1")    ## Connect and check Connection state    def_trytoconnect (self):if(Self.db.open ()):Print "Success"        Else:            Print "Failed to connect to MySQL"    ...

Common sql:

--CREATE TABLECreate Table if  not existsTest2 (IDinteger Primary Key, TimeReal, PowersReal);--Clear TableDelete  fromtest2;--InsertInsert  intoT1Values(1,0.1,0.2);--SelectSelect *  fromtest1--Delete TableDrop TableTest4

PYTHON+PYQT Database Basic Operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.