使用Python3操作MySQL資料庫:創建表,插入數據,查詢數據,更新數據,刪除數據。 ...
1、安裝MySQL驅動
pip install mysql-connector
安裝完成後進入命令行模式,導入驅動,如果不報錯,說明安裝成功
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mysql.connector
>>>
2、安裝MySQL
MySQL安裝請參考:https://www.cnblogs.com/webDepOfQWS/p/10685617.html
3、操作資料庫
MySQL操作資料庫的一般步驟如下:
a、建立連接
b、通過連接對象得到游標對象
c、執行SQL語句,獲取執行結果,如果執行的SQL語句會改變資料庫或表 ,需要提交,才會保存修改。
d、關閉游標對象,關閉連接對象。
創建表並插入數據
在rms資料庫中創建一張表:user_info並插入2條數據,創建表SQL語句如下:
create table user_info(
id int(10) primary key,
name char(20) not null,
passwd char(40) not null,
email char(20) not null,
phone char(20) not null,
role char(10) not null,
sex char(10) not null,
status int(10) not null,
createAt datetime not null,
exprAt datetime not null,
validDays int(10) not null,
delAt datetime
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
Python3代碼:
#coding:utf-8
#導入驅動
import mysql.connector
#建立連接
conn = mysql.connector.connect(host="127.0.0.1",user='root',database='rms',password='password')
#獲游標標對象
cursor = conn.cursor()
#SQL語句
SQL1='''create table user_info(
id int(10) primary key,
name char(20) not null,
passwd char(40) not null,
email char(20) not null,
phone char(20) not null,
role char(10) not null,
sex char(10) not null,
status int(10) not null,
createAt datetime not null,
exprAt datetime not null,
validDays int(10) not null,
delAt datetime
)ENGINE=InnoDB DEFAULT CHARSET=utf8;'''
SQL2='''insert into user_info values
(1,"StephenWang7","123456","[email protected]","15103887470","admin","male","200","20190412201130","20190419201130",30,null)'''
try:
#執行創建表的SQL語句
cursor.execute(SQL1)
#執行插入語句
cursor.execute(SQL2)
#提交
conn.commit()
except Exception as e:
print(e)
finally:
#關閉游標對象
cursor.close()
#關閉連接
conn.close
連接資料庫查看結果:
mysql> select count(*) from user_info;
+----------+
| count(*) |
+----------+
| 2 |
+----------+
1 row in set (0.27 sec)
mysql>
查詢SQL執行結果
fetchone():返回一條結果。
fetchall():返回所有結果。
fetchmany([size]):返回size條結果。
示例1:
try:
cursor.execute("select count(*) from user_info;")
#獲取執行結果
result = cursor.fetchone()
print(result)
except Exception as e:
print(e)
輸出1:
#返回的是一個tuple
(2,)
示例2:
查詢user_info表中所有的記錄。
try:
cursor.execute("select count(*) from user_info;")
#獲取執行結果,fatchone 只返回一條結果
result = cursor.fetchone()
print(result)
except Exception as e:
print(e)
運行示例2的代碼時,報錯:Unread result found,在連接資料庫時設置'buffered': True。
conn = mysql.connector.connect(host="127.0.0.1",user='root',database='rms',password='password',buffered=True)
輸出2:
(1, 'StephenWang7', '123456', '[email protected]', '15103887470', 'admin', 'male', 200, datetime.datetime(2019, 4, 12, 20, 11, 30), datetime.datetime(2019, 4, 19, 20, 11, 30), 30, None)
更新和刪除
更新和刪除的代碼與創建表類似,需要說明的一點是執行語句之後需要提交(commmit)。
#coding:utf-8
#導入驅動
import mysql.connector
#建立連接
conn = mysql.connector.connect(host="127.0.0.1",user='root',database='rms',password='password',buffered=True)
#獲游標標對象
cursor = conn.cursor()
try:
#執行更新語句
cursor.execute("update user_info set passwd=%s where id=%s",['py123456',1])
#獲取執行結果
result = cursor.fetchone()
print(result)
#提交
conn.commit()
except Exception as e:
print(e)
finally:
#關閉游標對象
cursor.close()
#關閉連接
conn.close
MySQL的占位符為%s,連接資料庫查看結果:
mysql> select passwd from user_info where id=1;
+----------+
| passwd |
+----------+
| py123456 |
+----------+
1 row in set (0.03 sec)