Python数据库访问之SQLite3、Mysql
現(xiàn)有的數(shù)據(jù)庫(kù)管理系統(tǒng)有很多種,本文選擇介紹兩種DBMS:SQLite 3 和 Mysql。
SQLite 3
SQLite 3是Python 3預(yù)裝的、相當(dāng)完備、無(wú)需配置的基于SQL的數(shù)據(jù)庫(kù)管理系統(tǒng)。要使用SQLite,只需導(dǎo)入sqlite3庫(kù),并使用Python標(biāo)準(zhǔn)化數(shù)據(jù)庫(kù)API來(lái)編程,而不用處理其他工作,比如:安裝數(shù)據(jù)庫(kù)、配置等等。
Python數(shù)據(jù)庫(kù)API?提供了一種標(biāo)準(zhǔn)機(jī)制,可以針各種各樣的數(shù)據(jù)庫(kù)管理系統(tǒng),包括SQLite。不管使用什么后臺(tái)數(shù)據(jù)庫(kù),代碼所遵循的過(guò)程都是一樣的:連接 -> 創(chuàng)建游標(biāo) -> 交互(利用游標(biāo),使用SQL管理數(shù)據(jù))->提交/回滾 ->關(guān)閉示例1:
#導(dǎo)入你需要的庫(kù) import sqlite3 #1、建立與數(shù)據(jù)庫(kù)的連接 connection=sqlite3.connect('test.db'); #2、創(chuàng)建數(shù)據(jù)游標(biāo) cursor=connection.cursor() #3、執(zhí)行一些SQL操作 cursor.execute("""select date('NOW')""") print(cursor.fetchone()) #4、提交所做的修改,使修改永久保留 connection.commit() #5、完成時(shí)關(guān)閉鏈接 connection.close()輸出:
('2013-06-26',)
示例2:
創(chuàng)建數(shù)據(jù)庫(kù) -> 插入數(shù)據(jù) -> 查詢
import sqlite3db='test.sqlite' #數(shù)據(jù)庫(kù)名 drop_table_sql="drop table if exists books;" create_table_sql=""" create table books(id integer primary key autoincrement unique not null,name text not null,price integer,publish_date date not null ); """connection=sqlite3.connect(db) cursor=connection.cursor()#創(chuàng)建數(shù)據(jù)庫(kù) cursor.execute(drop_table_sql) cursor.execute(create_table_sql)#插入數(shù)據(jù) insert_sql="insert into books (name,price,publish_date) values (?,?,?)"# ? 為占位符 cursor.execute(insert_sql,('java',123.23,'2012-12-03')) cursor.execute(insert_sql,('C++',83.23,'2013-02-03')) connection.commit()#查詢 select_sql = "SELECT * FROM books" cursor.execute(select_sql) #返回一個(gè)list,list中的對(duì)象類(lèi)型為tuple(元組) data=cursor.fetchall() for t in data:print(t)connection.close()輸出:
(1, 'java', 123.23, '2012-12-03')
(2, 'C++', 83.23, '2013-02-03')
?
Mysql
Mysql是非常流行的開(kāi)源關(guān)系性數(shù)據(jù)庫(kù)。
要使用Python訪問(wèn)Mysql,需要一個(gè)連接庫(kù),即對(duì)Python DB API的一個(gè)實(shí)現(xiàn),相當(dāng)于JAVA中的MySQL的JDBC Driver。其中比較著名就是MySQLdb(Django項(xiàng)目使用它),不過(guò),目前MySQLdb并不支持python3.x。我們只能采用其他連接庫(kù),MySQL官方已經(jīng)提供了MySQL連接器,而且已經(jīng)有支持Python3.x的版本了。
MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is compliant with the Python DB API version 2.0。
關(guān)于MySQL Connector/Python的各種介紹、安裝、API等文檔,請(qǐng)參考官網(wǎng):http://dev.mysql.com/doc/connector-python/en/index.html
示例:
import mysql.connector import sys, osuser = 'root' pwd = '123456' host = '127.0.0.1' db = 'test'connection = mysql.connector.connect(user=user, password=pwd, host=host, database=db) cursor = connection.cursor()#創(chuàng)建數(shù)據(jù)庫(kù)表 drop_table_sql="drop table if exists person;" create_table_sql = """ CREATE TABLE person(id int(10) AUTO_INCREMENT PRIMARY KEY,name varchar(20),age int(4) )CHARACTER SET utf8; """ try:cursor.execute(drop_table_sql)cursor.execute(create_table_sql) except mysql.connector.Error as err:print("create table 'mytable' failed.")print("Error: {}".format(err.msg))sys.exit()#插入數(shù)據(jù) insert_sql = 'INSERT INTO person(name, age) VALUES (%s,%s)' try:cursor.execute(insert_sql,('Jay', 22))cursor.execute(insert_sql,('Tony', 26))cursor.execute(insert_sql,('邵',24)) except mysql.connector.Error as err:print("insert table 'mytable' failed.")print("Error: {}".format(err.msg))sys.exit()#查詢數(shù)據(jù) select_sql = "SELECT * FROM person" try:#cursor.execute() 返回 None; 執(zhí)行SQL后的信息存儲(chǔ)在cursor對(duì)象內(nèi)。 cursor.execute(select_sql)#獲取一條記錄,每條記錄做為一個(gè)tuple(元組)返回data=cursor.fetchone()print(data)#獲取2條記錄,注意由于之前執(zhí)行有了fetchone(),所以游標(biāo)已經(jīng)指到第二條記錄了,也就是從第二條開(kāi)始的2條記錄data=cursor.fetchmany(2)print(data)cursor.execute(select_sql)#獲取所有結(jié)果 data=cursor.fetchall()print(data)cursor.execute(select_sql)#獲取所有結(jié)果for (id, name, age) in cursor:print("ID:{} Name:{} Age:{}".format(id, name, age))except mysql.connector.Error as err:print("query table 'mytable' failed.")print("Error: {}".format(err.msg))sys.exit()connection.commit() cursor.close() connection.close()輸出:
(1, 'Jay', 22)
[(2, 'Tony', 26), (3, '邵', 24)]
[(1, 'Jay', 22), (2, 'Tony', 26), (3, '邵', 24)]
ID:1 Name:Jay Age:22
ID:2 Name:Tony Age:26
ID:3 Name:邵 Age:24
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/windlaughing/p/3157531.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Python数据库访问之SQLite3、Mysql的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何配置一个Oracle服务
- 下一篇: yii2 migrate 数据库迁移的简