Python数据库访问之SQLite3、Mysql
現有的數據庫管理系統有很多種,本文選擇介紹兩種DBMS:SQLite 3 和 Mysql。
SQLite 3
SQLite 3是Python 3預裝的、相當完備、無需配置的基于SQL的數據庫管理系統。要使用SQLite,只需導入sqlite3庫,并使用Python標準化數據庫API來編程,而不用處理其他工作,比如:安裝數據庫、配置等等。
Python數據庫API?提供了一種標準機制,可以針各種各樣的數據庫管理系統,包括SQLite。不管使用什么后臺數據庫,代碼所遵循的過程都是一樣的:連接 -> 創建游標 -> 交互(利用游標,使用SQL管理數據)->提交/回滾 ->關閉示例1:
#導入你需要的庫 import sqlite3 #1、建立與數據庫的連接 connection=sqlite3.connect('test.db'); #2、創建數據游標 cursor=connection.cursor() #3、執行一些SQL操作 cursor.execute("""select date('NOW')""") print(cursor.fetchone()) #4、提交所做的修改,使修改永久保留 connection.commit() #5、完成時關閉鏈接 connection.close()輸出:
('2013-06-26',)
示例2:
創建數據庫 -> 插入數據 -> 查詢
import sqlite3db='test.sqlite' #數據庫名 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()#創建數據庫 cursor.execute(drop_table_sql) cursor.execute(create_table_sql)#插入數據 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) #返回一個list,list中的對象類型為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是非常流行的開源關系性數據庫。
要使用Python訪問Mysql,需要一個連接庫,即對Python DB API的一個實現,相當于JAVA中的MySQL的JDBC Driver。其中比較著名就是MySQLdb(Django項目使用它),不過,目前MySQLdb并不支持python3.x。我們只能采用其他連接庫,MySQL官方已經提供了MySQL連接器,而且已經有支持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。
關于MySQL Connector/Python的各種介紹、安裝、API等文檔,請參考官網: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()#創建數據庫表 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()#插入數據 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()#查詢數據 select_sql = "SELECT * FROM person" try:#cursor.execute() 返回 None; 執行SQL后的信息存儲在cursor對象內。 cursor.execute(select_sql)#獲取一條記錄,每條記錄做為一個tuple(元組)返回data=cursor.fetchone()print(data)#獲取2條記錄,注意由于之前執行有了fetchone(),所以游標已經指到第二條記錄了,也就是從第二條開始的2條記錄data=cursor.fetchmany(2)print(data)cursor.execute(select_sql)#獲取所有結果 data=cursor.fetchall()print(data)cursor.execute(select_sql)#獲取所有結果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
?
?
轉載于:https://www.cnblogs.com/windlaughing/p/3157531.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Python数据库访问之SQLite3、Mysql的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何配置一个Oracle服务
- 下一篇: 2013暑期规划