python-操作數據庫
python DB-API介紹
1.python標準數據庫接口為 python DB-API,python DB-API為開發人員提供了數據庫應用標稱接口
2.python數據庫接口支持非常多的數據庫,可以選擇適合你項目的數據庫:
MySQL
PostgreSQL
Microsoft SQL Server 2000
Oracle
Sybase
具體查看:https://wiki.python.org/moin/DatabaseInterfaces
不同的數據庫,就需要下載不同的DB API模塊,例如訪問Oracle數據庫和MySQL數據庫,需要下載Oracle和MySQL數據庫模塊
DB-API是一個規範,它定義一個系列必須的對象和數據庫存取方式,以便各種各樣的底層數據庫系統和多種多樣的數據庫接口程序提供一致的訪問接口.
python的DB-API,為大多數數據庫實現了接口,使用它連接各種數據庫後,就可以使用相同的方式操作各種數據庫
通用步驟:
1.引入模塊
2.獲取與數據庫的連接
3.執行SQL語句和存儲過程
4.關閉數據庫連接
什麽是MySQLdb?
MySQLdb是用於python連接Mysql數據庫的接口,它實現了python數據庫API規範V2.0,基於MySQL C API上簡歷的
1.安裝好mysql
2.導入python與mysql DB API模塊
import mysql.connector #先安裝mysql-connector-python-1.0.12-py3.3,再引入包 #創建鏈接數據庫 config={‘host‘:‘127.0.0.1‘,#默認127.0.0.1 ‘user‘:‘root‘, ‘password‘:‘vertrigo‘, ‘port‘:3306,#默認即為3306 ‘database‘:‘test‘, ‘charset‘:‘utf8‘#默認即為utf8 } try: cnn=mysql.connector.connect(**config)#connect方法加載config的配置進行數據庫的連接,完成後用一個變量進行接收 except mysql.connector.Error as e:print(‘數據庫鏈接失敗!‘,str(e))
else:#try沒有異常的時候才會執行
print("sucessfully!")
結果:
sucessfully!
接著上面,建表
#建表 sql_create_table=‘CREATE TABLE`student`(`id`int(10)NOT NULL AUTO_INCREMENT,`name`varchar(10) DEFAULT NULL,`age`int(3) DEFAULT NULL,PRIMARY KEY(`id`))ENGINE=MyISAM DEFAULT CHARSET = utf8‘ #獲取執行的權限,利用數據庫連接的返回,調用cursor方法獲取一個標記位,再去操作數據庫 #再通過標記位,去操作數據庫 cursor = cnn.cursor(buffered = True)#buffered=True會把結果集保存到本地並一次性返回,這樣可以提高性能 try: cursor.execute(sql_create_table)#執行sql語句 except mysql.connector.Error as e: print(‘創建表失敗!‘,str(e))
接著上面,添加數據
#插入數據庫 cursor = cnn.cursor(buffered=True)#獲取插入的標記位 try: #第一種:直接字符串插入方式 #表中的id是自增長,所以不用傳id #sql_insert1="insert into student(name,age) values (‘orange‘,20)" #cursor.execute(sql_insert1) #第二種:元組連接插入方式 sql_insert2="insert into student(name,age) values (%s,%s)" #此處的%s為占位符,而不是格式化字符串,所以age用%s data = (‘xiongrun‘,18)#元組的形式傳入兩個值 cursor.execute(sql_insert2,data)#執行插入 #數據庫的存儲一類引擎為Innodb,執行完成後需執行commit進行事務提交 #cnn.commit() #cursor.execute(‘commit‘) #當前的練習用的存儲引擎為MyISAM,不用執行commit #執行execute時就已經執行事務提交 #第三種:可以一次插入多條,效率比一條條插高,用的方法是executemany stmt = ‘insert into student(name,age) values (%s,%s)‘ data = [ (‘xiongrun1‘,21), (‘xiongrun2‘,22), (‘xiongrun3‘,21)] cursor.executemany(stmt,data) except mysql.connector.Error as e: print(‘插入數據報錯!‘,str(e)) finally:#無論如何都會執行下面的語句 cursor.close()#關閉標記位 cnn.close()#關閉數據庫鏈接
接上面,查詢數據
#查詢 cursor = cnn.cursor(buffered = True)#獲取查詢的標記位 try: #第一種 sql_query1=‘select id,name from student where age > %s‘ cursor.execute(sql_query1,(1,))#固定格式,記住 values = cursor.fetchall()#符合條件的所有數據,全部賦值給values print(‘所有數據:‘,values) #第二種 sql_query2 = ‘select * from student‘ cursor.execute(sql_query2) #加[0]代表返回第一個字段,如果想返回一條完整的數據就不要加 result1 = cursor.fetchone() print("一條數據:",result1) result2 = cursor.fetchone()[0] print("第一個字段:",result2) result3 = cursor.fetchmany(2)#返回2行數據 print("前2條數據:",result3) except mysql.connector.Error as e: print(‘查詢數據報錯!‘,str(e)) finally: cursor.close()#關閉標記位 cnn.close()#關閉數據庫鏈接
接上面,刪除
cursor = cnn.cursor() try: sql_delete=‘delete from student where name = %s and age < %s‘ data = (‘xiongrun‘,22) cursor.execute(sql_delete,data) except mysql.connector.Error as e: print(‘刪除錯誤‘,str(e)) finally: cursor.close()#關閉標記位 cnn.close()#關閉數據庫鏈接
結果:
練習:
手工創建一個表(表引擎為myisam),然後利用python對這表進行先插入再查詢的操作
create table student_myisam (id int(10) not null auto_increment,name varchar(10) default
null,age int(3) default null,primary key (id))engine = myisam default charset = utf8;
手動創建表student_myisam
import mysql.connector #先安裝mysql-connector-python-1.0.12-py3.3,再引入包 #創建鏈接數據庫 config={‘host‘:‘127.0.0.1‘,#默認127.0.0.1 ‘user‘:‘root‘, ‘password‘:‘vertrigo‘, ‘port‘:3306,#默認即為3306 ‘database‘:‘test‘, ‘charset‘:‘utf8‘#默認即為utf8 } try: cnn=mysql.connector.connect(**config)#connect方法加載config的配置進行數據庫的連接,完成後用一個變量進行接收 except mysql.connector.Error as e: print(‘數據庫鏈接失敗!‘,str(e)) else:#try沒有異常的時候才會執行 print("sucessfully!") #插入數據庫 cursor = cnn.cursor(buffered=True)#獲取插入的標記位 try: sql_insert1="insert into student_myisam(name,age) values (%s,%s)" #此處的%s為占位符,而不是格式化字符串,所以age用%s data = (‘xiongrun‘,18)#元組的形式傳入兩個值 cursor.execute(sql_insert1,data)#執行插入 except mysql.connector.Error as e: print(‘插入數據報錯!‘,str(e)) #查詢數據 try: sql_query2=‘select id,name from student_myisam where age > %s‘ cursor.execute(sql_query2,(1,))#固定格式,記住 values = cursor.fetchall()#符合條件的所有數據,全部賦值給values print(‘所有數據:‘,values) except mysql.connector.Error as e: print(‘查詢數據報錯!‘,str(e)) finally: cursor.close()#關閉標記位 cnn.close()#關閉數據庫鏈接
結果:
sucessfully!
所有數據: [(1, ‘xiongrun‘)]
手工創建一個表(表引擎為innodb),然後利用python對這個表進行先插入再查詢的操作
create table student_innodb (id int(10) not null auto_increment,name varchar(10) default
null,age int(3) default null,primary key (id))engine = innodb default charset = utf8;
手工創建student_innodb成功
1 import mysql.connector #先安裝mysql-connector-python-1.0.12-py3.3,再引入包 2 3 #創建鏈接數據庫 4 config={‘host‘:‘127.0.0.1‘,#默認127.0.0.1 5 ‘user‘:‘root‘, 6 ‘password‘:‘vertrigo‘, 7 ‘port‘:3306,#默認即為3306 8 ‘database‘:‘test‘, 9 ‘charset‘:‘utf8‘#默認即為utf8 10 } 11 try: 12 cnn=mysql.connector.connect(**config)#connect方法加載config的配置進行數據庫的連接,完成後用一個變量進行接收 13 except mysql.connector.Error as e: 14 print(‘數據庫鏈接失敗!‘,str(e)) 15 else:#try沒有異常的時候才會執行 16 print("sucessfully!") 17 18 cursor = cnn.cursor(buffered=True)#獲取插入的標記位 19 20 #插入數據庫 21 try: 22 sql_insert1="insert into student_innodb(name,age) values (%s,%s)" 23 #此處的%s為占位符,而不是格式化字符串,所以age用%s 24 data = (‘xiongrun1‘,20)#元組的形式傳入兩個值 25 cursor.execute(sql_insert1,data)#執行插入 26 #表引擎是innodb,需要執行下面兩句,進行事務提交,否則會報錯 27 cnn.commit() 28 cursor.execute(‘commit‘) 29 except mysql.connector.Error as e: 30 print(‘插入數據報錯!‘,str(e)) 31 32 #查詢數據 33 try: 34 sql_query2=‘select id,name from student_innodb where age > %s‘ 35 cursor.execute(sql_query2,(1,))#固定格式,記住 36 values = cursor.fetchall()#符合條件的所有數據,全部賦值給values 37 print(‘所有數據:‘,values) 38 except mysql.connector.Error as e: 39 print(‘查詢數據報錯!‘,str(e)) 40 finally: 41 cursor.close()#關閉標記位 42 cnn.close()#關閉數據庫鏈接
結果:
sucessfully!
所有數據: [(1, ‘xiongrun1‘)]
python-操作數據庫