Python3結構化資料庫操作包pymysql
阿新 • • 發佈:2019-02-02
以下程式碼實現環境是mac系統,本地配置mysql服務端和navicat premium客戶端,python環境是配置了pymysql的anaconda3。
首先,與資料庫建立connection和進行操作的原理
(1)通過navicat premium建立testdataset資料庫和庫內資料表test:
CREATE TABLE `test` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`age` int(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
(2)在test資料表裡新增資料項
(3)jupyter notebook裡連線資料庫,並對資料庫進行操作
import pandas as pd
import datetime
import pymysql
#建立連線
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
passwd='******', db='testdataset', charset='utf8' )#passwd是本地mysql伺服器密碼
conn
#Output:<pymysql.connections.Connection at 0x11443e588>
#建立遊標
cursor = conn.cursor()
cursor
#Output:<pymysql.cursors.Cursor at 0x11443e2e8>
#執行SQL,並返回受影響行數
effect_row = cursor.execute("select * from test")
effect_row
#Output:4
#獲取剩餘結果的第一行資料
r1=cursor.fetchone()
r1
#Output:(1, '李明', 18)
name='王天'
age=17
sql="select name,age from test where name='%s' and age='%s'" % (name,age)
row_count=cursor.execute(sql)
row_1 = cursor.fetchone()
print(row_count,row_1)
#Output:1 ('王天', 17)
conn.commit()
cursor.close()
conn.close()