1. 程式人生 > >Python3 使用pymysql庫操作mysql

Python3 使用pymysql庫操作mysql

1.先安裝好mysql及pymysql庫。

pip install pymysql

2.連線mysql.


In [1]: import pymysql

In [2]: db = pymysql.connect(host = 'localhost',user = 'root',password = '123456',
   ...: port = 3306)

In [3]: cursor = db.cursor()  #設定遊標

In [4]: cursor.execute('SELECT VERSION()')    #SQL語句,查詢版本資訊
Out[4]: 1

In [5]: cursor.fetchone()
Out[5]: ('5.7.23',)

In [6]: db.close()   #關閉連線

3.建立新的SQL庫

In [7]: sql = "CREATE DATABASE movies DEFAULT CHARACTER SET utf8"  #新建一個movies資料庫

In [8]: cursor.execute(sql)
Out[8]: 1

開啟mysql的視覺化工具可以看到,資料庫已經建立成功。

4.連線到movies資料庫

In [10]: db = pymysql.connect(host = 'localhost',user = 'root',password = '12345
    ...: 6',port = 3306,db = "movies")

5.新建一張表

In [11]: sql = 'CREATE TABLE IF NOT EXISTS movies(movie VARCHAR(255) NOT NULL,a
    ...: ctor VARCHAR(255) NOT NULL,score VARCHAR(255) NOT NULL,realse VARCHAR(
    ...: 255) NOT NULL,PRIMARY KEY(movie))'

In [12]: cursor.execute(sql)
Out[12]: 0

可以看到,表已經建立成功了。

 

6.插入資料

In [13]: movie = "倩女幽魂"

In [14]: actor = "張國榮,王祖賢,午馬"

In [15]: score = "8.8"

In [16]: realse = "2011-04-30"

In [17]: sql = "INSERT INTO movies(movie,actor,score,realse) values(%s,%s,%s,%s
    ...: )"

In [18]: try:
    ...:     cursor.execute(sql,(movie,actor,score,realse))
    ...:     db.commit()
    ...: except:
    ...:     db.rollback()
    ...:

開啟mysql視覺化工具,可以看到,已經插入成功。

7.查詢資料。假定該表中有如下資料:

In [19]: sql = "SELECT * FROM movies"

In [19]: try:
    ...:     cursor.execute(sql)
    ...:     data = cursor.fetchone()
    ...:     while data:
    ...:         print (data)
    ...:         data = cursor.fetchone()
    ...: except:
    ...:     print ("Error!")
    ...:
('倩女幽魂', '張國榮,王祖賢,午馬', '8.8', '2011-04-30')
('加勒比海盜', '約翰尼·德普,凱拉·奈特莉,奧蘭多·布魯姆', '8.9', '2003-11-21')
('唐伯虎點秋香', '周星馳,鞏俐,鄭佩佩', '9.2', '1993-07-01(中國香港)')

8.更新資料

In [20]: sql = 'UPDATE movies SET score = %s WHERE movie = %s'

In [21]: try:
    ...:     cursor.execute(sql,("9.9","倩女幽魂"))  #更改倩女幽魂的評分為9.9分
    ...:     db.commit()   #該語句一定要寫,否則更新無效
    ...: except:
    ...:     db.rollback()
    ...:

In [22]: sql = "SELECT * FROM movies WHERE movie = '倩女幽魂'"

In [23]: cursor.execute(sql)
Out[23]: 1

In [24]: cursor.fetchone()
Out[24]: ('倩女幽魂', '張國榮,王祖賢,午馬', '9.9', '2011-04-30')     #評分以改為9.9分

9.刪除資料

In [25]: sql = "DELETE FROM movies WHERE movie = '倩女幽魂'"  #刪除倩女幽魂這條資料

In [26]: try:
    ...:     cursor.execute(sql)
    ...:     db.commit()
    ...: except:
    ...:     db.rollback()
    ...:

In [27]: sql = "SELECT * FROM movies"

In [28]: cursor.execute(sql)
Out[28]: 2

In [29]: cursor.fetchall()  #結果顯示倩女幽魂的資料以刪除
Out[29]:
(('加勒比海盜', '約翰尼·德普,凱拉·奈特莉,奧蘭多·布魯姆', '8.9', '2003-11-21')
,
 ('唐伯虎點秋香', '周星馳,鞏俐,鄭佩佩', '9.2', '1993-07-01(中國香港)'))    

In [30]:

10.刪除所有資料而不刪除表

In [30]: sql = "TRUNCATE TABLE movies"

In [31]: cursor.execute(sql)
Out[31]: 0

In [32]: sql = "SELECT * FROM movies"

In [33]: cursor.execute(sql)
Out[33]: 0

In [34]: cursor.fetchone()   #無一條資料,說明已全部刪除

In [35]: