Python+PyQt 資料庫基本操作

來源:互聯網
上載者:User

標籤:style   blog   io   ar   color   os   使用   sp   資料   

Sqlite:

使用Python的sqlite3:

需要注意下commit方式與qt稍有不同

import sqlite3class DBManager():    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()    ...

 

使用QtSql:

 1 from PyQt4.QtSql import QSqlQuery,QSqlDatabase 2  3 class DBManager(): 4     def __init__(self): 5         self.db = QSqlDatabase.addDatabase("QSQLITE") #select database type 6         self.db.setDatabaseName("core.db") # set database name 7         self.db.open()  #connect to or create database   8         self.query = QSqlQuery() #sql handler 9         ...    10     11     ...

 

Mysql:

from PyQt4.QtSql import QSqlQuery,QSqlDatabaseclass DBManager():    def __init__(self):        self.db = QSqlDatabase.addDatabase("QMYSQL")  #select database type        self.db.setHostName("localhost")  #set address        self.db.setUserName("root"); #set user name        self.db.setPassword("root"); #set user pwd        self._trytoConnect() #check connection        self.query = QSqlQuery()        ## create database        self.query.exec_("CREATE DATABASE test1")        ## Choose database        self.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"    ...

 

常用SQL:

--create tablecreate table if not exists test2 (id integer primary key,time real,powers real);--clear tabledelete from test2;--insertinsert into t1 values(1,0.1,0.2);--selectselect * from test1--delete tabledrop table test4

 

Python+PyQt 資料庫基本操作

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.