31-32 python mysql-connector创建数据、crud,where,排序,删除等。PyMSQL驱动,插入操作、查询操作、更新操作、删除操作、执行
31Python MysSQL - mysql-connector驅(qū)動
使用pip命令安裝mysql-connector:
python -m pip install mysql-connector效果圖如下(如果使用的是Anaconda,需要進入它的命令行窗口,執(zhí)行如下操作):
使用以下代碼測試mysql-connector是否安裝成功:
執(zhí)行以上代碼,如果沒有產(chǎn)生錯誤,表明安裝成功。
**注意:**如果你的 MySQL 是 8.0 版本,密碼插件驗證方式發(fā)生了變化,早期版本為 mysql_native_password,8.0 版本為 caching_sha2_password,所以需要做些改變:
先修改 my.ini 配置:
然后在 mysql 下執(zhí)行以下命令來修改密碼:
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '新密碼';更多內(nèi)容可以參考:Python MySQL8.0 鏈接問題(https://www.runoob.com/note/45833)
31.1創(chuàng)建數(shù)據(jù)庫連接
可以使用以下代碼來連接數(shù)據(jù)庫:
import mysql.connectormydb = mysql.connector.connect(host="localhost", # 數(shù)據(jù)庫主機地址user="yourusername", # 數(shù)據(jù)庫用戶名passwd="yourpassword" # 數(shù)據(jù)庫密碼 )print(mydb)31.2創(chuàng)建數(shù)據(jù)庫
創(chuàng)建數(shù)據(jù)庫使用 “CREATE DATABASE” 語句,以下創(chuàng)建一個名為 runoob_db 的數(shù)據(jù)庫:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",password="123456" )mycursor = mydb.cursor()mycursor.execute("CREATE DATABASE runoob_db")打開mysql的GUI客戶端,可以看到如下效果:
31.3創(chuàng)建數(shù)據(jù)庫表
創(chuàng)建數(shù)據(jù)表使用”CREATE TABLE”語句,創(chuàng)建數(shù)據(jù)表前,需要確保數(shù)據(jù)庫已存在,以下創(chuàng)建一個名為sites的數(shù)據(jù)表:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor() mycursor.execute("CREATE TABLE sites (name VARCHAR(255), url VARCHAR(255))")執(zhí)行成功后,我們可以看到數(shù)據(jù)庫創(chuàng)建的數(shù)據(jù)表sites,字段為name和url
我們也可以使用”SHOW TABLES”來查看數(shù)據(jù)表是否已存在:
運行結(jié)果:
('sites',)31.3.1主鍵設(shè)置
創(chuàng)建表的時候我們一般都會設(shè)置一個主鍵(PRIMARY KEY),我們可以使用 “INT AUTO_INCREMENT PRIMARY KEY” 語句來創(chuàng)建一個主鍵,主鍵起始值為 1,逐步遞增。
如果我們的表已經(jīng)創(chuàng)建,我們需要使用 ALTER TABLE 來給表添加主鍵:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()mycursor.execute("ALTER TABLE sites ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY");也可以在表還沒創(chuàng)建的時候,一步到位,將主鍵添加上去。
31.4插入數(shù)據(jù)
插入數(shù)據(jù)使用”INSERT INTO”語句:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()sql = "INSERT INTO sites(name,url) VALUES (%s,%s)" val = ("RUNOOB","https://www.runoob.com") mycursor.execute(sql,val)mydb.commit() #數(shù)據(jù)表內(nèi)容有更新,必須使用到該語句 print(mycursor.rowcount,"條記錄插入成功。")運行結(jié)果:
1 條記錄插入成功。31.5批量插入
批量插入使用executemany()方法,該方法的第二個參數(shù)是一個元組列表,包含了我們要插入的數(shù)據(jù):
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()sql = "INSERT INTO sites(name,url) VALUES (%s,%s)" val = [('Google','http://www.google.com'),('Github','https://www.github.com'),('Taobao','https://www.taobao.com'),('stackoverflow','https://www.stackoverflow.com') ] mycursor.executemany(sql,val)mydb.commit() #數(shù)據(jù)表內(nèi)容有更新,必須使用該語句 print(mycursor.rowcount,"條記錄插入成功。")運行結(jié)果:
4 條記錄插入成功。執(zhí)行以上代碼后,我們可以看看數(shù)據(jù)表的記錄:
如果我們想在數(shù)據(jù)記錄插入后,獲取該記錄的ID,可以使用以下代碼:
運行結(jié)果:
1 條記錄已插入,ID: 631.6查詢數(shù)據(jù)
查詢數(shù)據(jù)使用SELECT語句:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()mycursor.execute("SELECT * FROM sites")myresult = mycursor.fetchall() #fetchall()獲取所有記錄for x in myresult:print(x)運行結(jié)果:
('RUNOOB', 'https://www.runoob.com', 1) ('Google', 'http://www.google.com', 2) ('Github', 'https://www.github.com', 3) ('Taobao', 'https://www.taobao.com', 4) ('stackoverflow', 'https://www.stackoverflow.com', 5) ('Zhihu', 'https://www.zhihu.com', 6)也可以讀取指定的字段數(shù)據(jù):
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()mycursor.execute("SELECT name,url FROM sites")myresult = mycursor.fetchall() #fetchall()獲取所有記錄for x in myresult:print(x)運行結(jié)果:
('RUNOOB', 'https://www.runoob.com') ('Google', 'http://www.google.com') ('Github', 'https://www.github.com') ('Taobao', 'https://www.taobao.com') ('stackoverflow', 'https://www.stackoverflow.com') ('Zhihu', 'https://www.zhihu.com')如果我們只想讀取一條記錄,可以使用fetchone()方法:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()mycursor.execute("SELECT name,url FROM sites")myresult = mycursor.fetchone()print(myresult)運行結(jié)果:
('RUNOOB', 'https://www.runoob.com')31.7Where條件語句
如果我們要讀指定條件的數(shù)據(jù),可以使用where語句
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()# sql = "SELECT * FROM sites WHERE url LIKE '%oo%'" sql = "SELECT * FROM sites WHERE name = 'RUNOOB'" mycursor.execute(sql)myresult = mycursor.fetchall()for x in myresult:print(x)執(zhí)行結(jié)果:
('RUNOOB', 'https://www.runoob.com', 1)為了防止數(shù)據(jù)查詢發(fā)生SQL注入的攻擊,我們可以使用%s占位符來轉(zhuǎn)義查詢的條件:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()sql = "SELECT * FROM sites WHERE name = %s" na = ("RUNOOB",)mycursor.execute(sql,na)myresult = mycursor.fetchall()for x in myresult:print(x)運行結(jié)果:
('RUNOOB', 'https://www.runoob.com', 1)31.8排序
查詢結(jié)果排序可以使用ORDER BY語句,默認的排序方式為升序,關(guān)鍵字為ASC,如果要設(shè)置降序排序,可以設(shè)置關(guān)鍵字DESC。
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()# sql = "SELECT * FROM sites LIMIT 3" # sql = "SELECT * FROM sites LIMIT 3 OFFSET 1" # sql = "SELECT * FROM sites ORDER BY name DESC" sql = "SELECT * FROM sites ORDER BY name"mycursor.execute(sql)myresult = mycursor.fetchall()for x in myresult:print(x)運行結(jié)果:
('Github', 'https://www.github.com', 3) ('Google', 'http://www.google.com', 2) ('RUNOOB', 'https://www.runoob.com', 1) ('stackoverflow', 'https://www.stackoverflow.com', 5) ('Taobao', 'https://www.taobao.com', 4) ('Zhihu', 'https://www.zhihu.com', 6)31.9刪除記錄
刪除記錄使用”DELETE FROM”語句
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()sql = "DELETE FROM sites WHERE name = 'stackoverflow'" mycursor.execute(sql)mydb.commit() print(mycursor.rowcount,"條記錄刪除")運行結(jié)果:
1 條記錄刪除
注意:要慎重使用刪除語句,刪除語句要確保指定了 WHERE 條件語句,否則會導致整表數(shù)據(jù)被刪除。
為了防止數(shù)據(jù)庫查詢發(fā)生SQL注入的攻擊,我們可以使用%s占位符來轉(zhuǎn)義刪除語句的條件
31.10更新表數(shù)據(jù)
數(shù)據(jù)表更新用”UPDATE”語句:
# -*- coding: UTF-8 -*-import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" )mycursor = mydb.cursor()sql = "UPDATE sites SET NAME = 'ZH' WHERE name='Zhihu'" mycursor.execute(sql)mydb.commit() print(mycursor.rowcount,"條記錄被更新")注意: UPDATE 語句要確保指定了 WHERE 條件語句,否則會導致整表數(shù)據(jù)被更新。
為了防止數(shù)據(jù)庫查詢發(fā)生 SQL 注入的攻擊,我們可以使用 %s 占位符來轉(zhuǎn)義更新語句的條件:
import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" ) mycursor = mydb.cursor()sql = "UPDATE sites SET name = %s WHERE name = %s" val = ("Zhihu", "ZH")mycursor.execute(sql, val)mydb.commit()print(mycursor.rowcount, " 條記錄被修改")31.11刪除表
刪除表使用 “DROP TABLE” 語句, IF EXISTS 關(guān)鍵字是用于判斷表是否存在,只有在存在的情況才刪除:
import mysql.connectormydb = mysql.connector.connect(host="localhost",user="root",passwd="123456",database="runoob_db" ) mycursor = mydb.cursor()sql = "DROP TABLE IF EXISTS sites" # 刪除數(shù)據(jù)表 sitesmycursor.execute(sql)32Python3 MySQL數(shù)據(jù)庫連接 - PyMySQL驅(qū)動
32.1什么是PyMySQL安裝?
PyMySQL 是在 Python3.x 版本中用于連接 MySQL 服務器的一個庫,Python2中則使用mysqldb。
PyMySQL 遵循 Python 數(shù)據(jù)庫 API v2.0 規(guī)范,并包含了 pure-Python MySQL 客戶端庫。
32.2PyMySQL安裝
在使用PyMySQL之前,我們需要確保PyMySQL已安裝。
PyMySQL下載地址:https://github.com/PyMySQL/PyMySQL。
如果還未安裝,我們可以使用以下命令安裝最新版的PyMySQL:
如果你的系統(tǒng)不支持 pip 命令,可以使用以下方式安裝:
1、使用 git 命令下載安裝包安裝(你也可以手動下載):
$ git clone https://github.com/PyMySQL/PyMySQL $ cd PyMySQL/ $ python3 setup.py install2、如果需要制定版本號,可以使用 curl 命令來安裝:
$ # X.X 為 PyMySQL 的版本號 $ curl -L https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz $ cd PyMySQL* $ python3 setup.py install $ # 現(xiàn)在你可以刪除 PyMySQL* 目錄注意:請確保您有root權(quán)限來安裝上述模塊。
安裝的過程中可能會出現(xiàn)"ImportError: No module named setuptools"的錯誤提示,意思是你沒有安裝setuptools,你可以訪問https://pypi.python.org/pypi/setuptools 找到各個系統(tǒng)的安裝方法。
Linux 系統(tǒng)安裝實例:
$ wget https://bootstrap.pypa.io/ez_setup.py $ python3 ez_setup.py32.3數(shù)據(jù)庫連接
連接數(shù)據(jù)庫前,請先確認以下事項:
?您已經(jīng)創(chuàng)建了數(shù)據(jù)庫 TESTDB.
?在TESTDB數(shù)據(jù)庫中您已經(jīng)創(chuàng)建了表 EMPLOYEE
?EMPLOYEE表字段為 FIRST_NAME, LAST_NAME, AGE, SEX 和 INCOME。
?連接數(shù)據(jù)庫TESTDB使用的用戶名為 “testuser” ,密碼為 “test123”,你可以可以自己設(shè)定或者直接使用root用戶名及其密碼,Mysql數(shù)據(jù)庫用戶授權(quán)請使用Grant命令。
?在你的機子上已經(jīng)安裝了 Python MySQLdb 模塊。
?如果您對sql語句不熟悉,可以訪問我們的 SQL基礎(chǔ)教程
實例:
以下實例鏈接MySQL的TESTDB數(shù)據(jù)庫:
運行結(jié)果:
Database version : 5.6.21-log32.4創(chuàng)建數(shù)據(jù)庫表
如果數(shù)據(jù)庫連接存在我們可以使用execute()方法來為數(shù)據(jù)庫創(chuàng)建表,如下所示創(chuàng)建表EMPLOYEE:
# -*- coding: UTF-8 -*-import pymysql#打開數(shù)據(jù)庫連接 db = pymysql.connect("localhost","root","123456","TESTDB")#使用cursor()方法創(chuàng)建一個游標對象cursor cursor = db.cursor()#使用 execute() 方法執(zhí)行 SQL,如果表存在則刪除 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")#使用預處理語句創(chuàng)建表 sql = """CREATE TABLE EMPLOYEE(FIRST_NAME CHAR(20) NOT NULL,LAST_NAME CHAR(20),AGE INT,SEX CHAR(1),INCOME FLOAT)"""cursor.execute(sql)#關(guān)閉數(shù)據(jù)庫連接 db.close()運行結(jié)果:
32.5數(shù)據(jù)庫插入操作
以下實例使用執(zhí)行 SQL INSERT 語句向表 EMPLOYEE 插入記錄:
# -*- coding: UTF-8 -*-import pymysql#打開數(shù)據(jù)庫連接 db = pymysql.connect("localhost","root","123456","TESTDB")#使用cursor()方法獲取操作游標 cursor = db.cursor()#SQL 插入語語句 sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME)VALUES('Mac','Mohan',20,'M',2000)"""try:#執(zhí)行sql語句cursor.execute(sql)#提交到數(shù)據(jù)庫執(zhí)行db.commit() except:#如果發(fā)生錯誤則回滾db.rollback()#關(guān)閉數(shù)據(jù)庫連接 db.close()運行結(jié)果:
以上例子也可以寫成如下形式:
運行結(jié)果:
32.6數(shù)據(jù)庫查詢操作
Python查詢Mysql使用fetchone()方法獲取單條數(shù)據(jù),使用fetchall()方法獲取多條數(shù)據(jù)。
?fetchone():該方法獲取下一個查詢結(jié)果集。結(jié)果集是一個對象。
?fetchall():接收全部的返回結(jié)果行。
?rowcount:這是一個只讀屬性,并返回執(zhí)行execute()方法后影響的行數(shù)。
實例:
查詢EMPLOYEE表中的salary(工資)字段大于1000的所有數(shù)據(jù):
運行結(jié)果:
fname=Mac,lname=Mohan,age=20,sex=M,income=2000.0 fname=Mac,lname=Mohan,age=20,sex=M,income=2000.032.7數(shù)據(jù)庫更新操作
更新操作用于更新數(shù)據(jù)表的的數(shù)據(jù),以下實例將 TESTDB 表中 SEX 為 ‘M’ 的 AGE 字段遞增 1:
# -*- coding: UTF-8 -*-import pymysql# 打開數(shù)據(jù)庫連接 db = pymysql.connect("localhost", "root", "123456", "TESTDB")# 使用cursor()方法獲取操作游標 cursor = db.cursor()# SQL 更新語句 sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 WHERE SEX = '%c'" % 'M' try:# 執(zhí)行SQL語句cursor.execute(sql)# 提交到數(shù)據(jù)庫執(zhí)行db.commit() except:# 發(fā)生錯誤時回滾db.rollback()# 關(guān)閉數(shù)據(jù)庫連接 db.close()運行結(jié)果:
上滿的結(jié)果是AGE的值增大了132.8刪除操作
刪除操作用于刪除數(shù)據(jù)表中的數(shù)據(jù),以下實例演示了刪除數(shù)據(jù)表EMPLOYEE中的AGE大于20的所有數(shù)據(jù):
# -*- coding: UTF-8 -*-import pymysql#打開數(shù)據(jù)庫連接 db = pymysql.connect("localhost","root","123456","TESTDB")#使用cursor()方法獲取操作游標 cursor = db.cursor()# SQL刪除語句 sql = "DELETE FROM EMPLOYEE WHERE AGE > %s" % 20try:#執(zhí)行SQL語句cursor.execute(sql)#提交修改db.commit() except:#發(fā)生錯誤時回滾db.rollback()#關(guān)閉連接 db.close()32.9執(zhí)行事務
事務機制可以確保數(shù)據(jù)一致性。
事務應該具有4個屬性:原子性、一致性、隔離性、持久性。這四個屬性通常稱為ACID特性。
?原子性(atomicity)。一個事務是一個不可分割的工作單位,事務中包括的諸操作要么都做,要么都不做。
?一致性(consistency)。事務必須是使數(shù)據(jù)庫從一個一致性狀態(tài)變到另一個一致性狀態(tài)。一致性與原子性是密切相關(guān)的。
?隔離性(isolation)。一個事務的執(zhí)行不能被其他事務干擾。即一個事務內(nèi)部的操作及使用的數(shù)據(jù)對并發(fā)的其他事務是隔離的,并發(fā)執(zhí)行的各個事務之間不能互相干擾。
?持久性(durability)。持續(xù)性也稱永久性(permanence),指一個事務一旦提交,它對數(shù)據(jù)庫中數(shù)據(jù)的改變就應該是永久性的。接下來的其他操作或故障不應該對其有任何影響。
Python DB API 2.0 的事務提供了兩個方法 commit 或 rollback。
對于支持事務的數(shù)據(jù)庫, 在Python數(shù)據(jù)庫編程中,當游標建立之時,就自動開始了一個隱形的數(shù)據(jù)庫事務。
commit()方法游標的所有更新操作,rollback()方法回滾當前游標的所有操作。每一個方法都開始了一個新的事務。
32.10錯誤處理
DB API中定義了一些數(shù)據(jù)庫操作的錯誤及異常,下表列出了這些錯誤和異常:
總結(jié)
以上是生活随笔為你收集整理的31-32 python mysql-connector创建数据、crud,where,排序,删除等。PyMSQL驱动,插入操作、查询操作、更新操作、删除操作、执行的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 特斯拉车辆在家充电需要预热电池吗特斯拉m
- 下一篇: linux cmake编译源码,linu