国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Python+MySQL數(shù)據(jù)庫操作
ModuleNotFoundError: No module named 'PyMySQL'
>>>
```
如果產(chǎn)生如上結果,則表示MySQLdb模塊尚未安裝。
最后一個穩(wěn)定版本可以在PyPI上使用,可以通過`pip`命令來安裝-
```shell
:/Users/Administrator> pip install PyMySQL
Collecting PyMySQL
Downloading PyMySQL-0.7.11-py2.py3-none-any.whl (78kB)
51% |████████████████▋ | 40kB 109kB/s eta 0:064% |████████████████████▊| 51kB 112kB/s eta77% |█████████████████████████| 61kB 135kB/s90% |█████████████████████████████ | 71kB 152100% |████████████████████████████████| 81kB 163kB/s
Installing collected packages: PyMySQL
Successfully installed PyMySQL-0.7.11
C:/Users/Administrator>
```
或者(例如,如果pip不可用),可以從GitHub下載tarball,并按照以下方式安裝:
```shell
$ # X.X is the desired PyMySQL version (e.g. 0.5 or 0.6).
$ curl -L http://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X | tar xz
$ cd PyMySQL*
$ python setup.py install
$ # The folder PyMySQL* can be safely removed now.
```
> 注意 - 確保具有root權限來安裝上述模塊。
## 3.數(shù)據(jù)庫連接
在連接到MySQL數(shù)據(jù)庫之前,請確保以下幾點:
- 已經(jīng)創(chuàng)建了一個數(shù)據(jù)庫:`test`。
- 已經(jīng)在`test`中創(chuàng)建了一個表:`employee`。
- `employee`表格包含:`fist_name`,`last_name`,`age`,`sex`和`income`字段。
- MySQL用戶“root”和密碼“123456”可以訪問:`test`。
- Python模塊PyMySQL已正確安裝在您的計算機上。
- 已經(jīng)通過[MySQL教程](http://www.yiibai.com/mysql "MySQL教程")了解MySQL基礎知識。
創(chuàng)建表`employee`的語句為:
```sql
CREATE TABLE `employee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`first_name` char(20) NOT NULL,
`last_name` char(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`income` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
**實例**
以下是Python通過PyMySQL模塊接口連接MySQL數(shù)據(jù)庫“`test`”的示例 -
> 注意:在 Windows 系統(tǒng)上,`import PyMySQL` 和 `import pymysql` 有區(qū)別。
```python
#!/usr/bin/python3
#coding=utf-8import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print ("Database version : %s " % data)
# disconnect from server
db.close()
```
運行此腳本時,會產(chǎn)生以下結果 -
```shell
Database version : 5.7.14-log
```
如果使用數(shù)據(jù)源建立連接,則會返回連接對象并將其保存到`db`中以供進一步使用,否則將`db`設置為`None`。 接下來,`db`對象用于創(chuàng)建一個游標對象,用于執(zhí)行SQL查詢。 最后,在結果打印出來之前,它確保數(shù)據(jù)庫連接關閉并釋放資源。
## 4.創(chuàng)建數(shù)據(jù)庫表
建立數(shù)據(jù)庫連接后,可以使用創(chuàng)建的游標的`execute`方法將數(shù)據(jù)庫表或記錄創(chuàng)建到數(shù)據(jù)庫表中。
**示例**
下面演示如何在數(shù)據(jù)庫:`test`中創(chuàng)建一張數(shù)據(jù)庫表:`employee` -
```python
#!/usr/bin/python3
#coding=utf-8import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Drop table if it already exist using execute() method.
cursor.execute("DROP TABLE IF EXISTS employee")
# Create table as per requirement
sql = """CREATE TABLE `employee` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`first_name` char(20) NOT NULL,
`last_name` char(20) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`sex` char(1) DEFAULT NULL,
`income` float DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
cursor.execute(sql)
print("Created table Successfull.")
# disconnect from server
db.close()
```
運行此腳本時,會產(chǎn)生以下結果 -
```shell
Created table Successfull.
```
## 5.插入操作
當要將記錄創(chuàng)建到數(shù)據(jù)庫表中時,需要執(zhí)行`INSERT`操作。
**示例**
以下示例執(zhí)行SQL的`INSERT`語句以在`EMPLOYEE`表中創(chuàng)建一條(多條)記錄 -
```python
#!/usr/bin/python3
#coding=utf-8import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Mac', 'Su', 20, 'M', 5000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
## 再次插入一條記錄
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME, AGE, SEX, INCOME)
VALUES ('Kobe', 'Bryant', 40, 'M', 8000)"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
print (sql)
print('Yes, Insert Successfull.')
# disconnect from server
db.close()
```
運行此腳本時,會產(chǎn)生以下結果 -
```shell
Yes, Insert Successfull.
```
上述插入示例可以寫成如下動態(tài)創(chuàng)建SQL查詢 -
```python
#!/usr/bin/python3
#coding=utf-8import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, /
LAST_NAME, AGE, SEX, INCOME) /
VALUES ('%s', '%s', '%d', '%c', '%d' )" % /
('Max', 'Su', 25, 'F', 2800)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
```
**示例**
以下代碼段是另一種執(zhí)行方式,可以直接傳遞參數(shù) -
```python
..................................
user_id = "test123"
password = "password"
con.execute('insert into Login values("%s", "%s")' % /
(user_id, password))
..................................
```
## 6.讀取操作
任何數(shù)據(jù)庫上的讀操作表示要從數(shù)據(jù)庫中讀取獲取一些有用的信息。
在建立數(shù)據(jù)庫連接后,就可以對此數(shù)據(jù)庫進行查詢了。 可以使用`fetchone()`方法獲取單條記錄或`fetchall()`方法從數(shù)據(jù)庫表中獲取多個值。
- `fetchone()` - 它獲取查詢結果集的下一行。 結果集是當使用游標對象來查詢表時返回的對象。
- `fetchall()` - 它獲取結果集中的所有行。 如果已經(jīng)從結果集中提取了一些行,則從結果集中檢索剩余的行。
- `rowcount` - 這是一個只讀屬性,并返回受`execute()`方法影響的行數(shù)。
**示例**
以下過程查詢`EMPLOYEE`表中所有記錄的工資超過`1000`員工記錄信息 -
```python
#!/usr/bin/python3
#coding=utf-8import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# 按字典返回
# cursor = db.cursor(pymysql.cursors.DictCursor)
# Prepare SQL query to select a record from the table.
sql = "SELECT * FROM EMPLOYEE /
WHERE INCOME > %d" % (1000)
#print (sql)
try:
# Execute the SQL command
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for row in results:
#print (row)
fname = row[1]
lname = row[2]
age = row[3]
sex = row[4]
income = row[5]
# Now print fetched result
print ("name = %s %s,age = %s,sex = %s,income = %s" % /
(fname, lname, age, sex, income ))
except:
import traceback
traceback.print_exc() print ("Error: unable to fetch data")
# disconnect from server
db.close()
```
```shell
name = Mac Su,age = 20,sex = M,income = 5000.0
name = Kobe Bryant,age = 40,sex = M,income = 8000.0
```
## 7.更新操作
UPDATE語句可對任何數(shù)據(jù)庫中的數(shù)據(jù)進行更新操作,它可用于更新數(shù)據(jù)庫中已有的一個或多個記錄。
以下程序將所有`SEX`字段的值為“`M`”的記錄的年齡(`age`字段)更新為增加一年。
```python
#!/usr/bin/python3
#coding=utf-8import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
#cursor = db.cursor()
cursor = db.cursor(pymysql.cursors.DictCursor)
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to UPDATE required records
sql = "UPDATE EMPLOYEE SET AGE = AGE + 1 /
WHERE SEX = '%c'" % ('M')
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
```
## 8.刪除操作
當要從數(shù)據(jù)庫中刪除一些記錄時,那么可以執(zhí)行`DELETE`操作。 以下是刪除`EMPLOYEE`中`AGE`超過`40`的所有記錄的程序 -
```python
#!/usr/bin/python3
#coding=utf-8import pymysql
# Open database connection
db = pymysql.connect("localhost","root","123456","test" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (40)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
# disconnect from server
db.close()
```
## 9.執(zhí)行事務
事務是確保數(shù)據(jù)一致性的一種機制。事務具有以下四個屬性 -
- **原子性** - 事務要么完成,要么完全沒有發(fā)生。
- **一致性** - 事務必須以一致的狀態(tài)開始,并使系統(tǒng)保持一致狀態(tài)。
- **隔離性** - 事務的中間結果在當前事務外部不可見。
- **持久性** - 當提交了一個事務,即使系統(tǒng)出現(xiàn)故障,效果也是持久的。Python DB API 2.0提供了兩種提交或回滾事務的方法。
**示例**
已經(jīng)知道如何執(zhí)行事務。 這是一個類似的例子 -
```python
# Prepare SQL query to DELETE required records
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
```
### 9.1.COMMIT操作
提交是一種操作,它向數(shù)據(jù)庫發(fā)出信號以完成更改,并且在此操作之后,不會更改任何更改。
下面是一個簡單的例子演示如何調用`commit()`方法。
```python
db.commit()
```
### 9.2.回滾操作
如果您對一個或多個更改不滿意,并且要完全還原這些更改,請使用`rollback()`方法。
下面是一個簡單的例子演示如何調用`rollback()`方法。
```python
db.rollback()
```
## 10.斷開數(shù)據(jù)庫連接
要斷開數(shù)據(jù)庫連接,請使用`close()`方法。
```python
db.close()
```
如果用戶使用`close()`方法關閉與數(shù)據(jù)庫的連接,則任何未完成的事務都將被數(shù)據(jù)庫回滾。 但是,您的應用程序不會依賴于數(shù)據(jù)級別的實現(xiàn)細節(jié),而是明確地調用提交或回滾。
## 11.處理錯誤
錯誤有很多來源。一些示例是執(zhí)行的SQL語句中的語法錯誤,連接失敗或為已取消或已完成語句句柄調用`fetch`方法等等。
DB API定義了每個數(shù)據(jù)庫模塊中必須存在的許多錯誤。下表列出了這些異常和錯誤 -
| 編號| 異常| 描述 |
| ------------ | ------------ | ------------ |
| 1| *Warning* |用于非致命問題,是*StandardError*的子類。 |
| 2| *Error*| 錯誤的基類,是*StandardError*的子類。|
| 3| *InterfaceError*| 用于數(shù)據(jù)庫模塊中的錯誤,但不是數(shù)據(jù)庫本身,是*Error*的子類。|
| 4| *DatabaseError*| 用于數(shù)據(jù)庫中的錯誤,是*Error*的子類。|
| 5| *DataError*|*DatabaseError*的子類引用數(shù)據(jù)中的錯誤。 |
| 6| *OperationalError*| *DatabaseError*的子類,涉及如丟失與數(shù)據(jù)庫的連接等錯誤。 這些錯誤通常不在Python腳本程序的控制之內。|
| 7| *IntegrityError*|*DatabaseError *子類錯誤,可能會損害關系完整性,例如唯一性約束和外鍵。 |
| 8| *InternalError*| *DatabaseError*的子類,指的是數(shù)據(jù)庫模塊內部的錯誤,例如游標不再活動。|
| 9| *ProgrammingError*| *DatabaseError*的子類,它引用錯誤,如錯誤的表名和其他安全。|
| 10 | *NotSupportedError*|*DatabaseError*的子類,用于嘗試調用不支持的功能。 |
Python腳本應該處理這些錯誤,但在使用任何上述異常之前,請確保您的PyMySQL支持該異常。 可以通過閱讀DB API 2.0規(guī)范獲得更多關于它們的信息。 
本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請點擊舉報。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Python+MySQL數(shù)據(jù)庫操作(PyMySQL)
Python連接MySQL數(shù)據(jù)庫之pymysql模塊使用
Python3 MySQL 數(shù)據(jù)庫連接 | 菜鳥教程
Python3操作MySQL數(shù)據(jù)庫
python爬蟲26 | 把數(shù)據(jù)爬取下來之后就存儲到你的MySQL數(shù)據(jù)庫。
干貨!python與MySQL數(shù)據(jù)庫的交互實戰(zhàn)
更多類似文章 >>
生活服務
分享 收藏 導長圖 關注 下載文章
綁定賬號成功
后續(xù)可登錄賬號暢享VIP特權!
如果VIP功能使用有故障,
可點擊這里聯(lián)系客服!

聯(lián)系客服