python基礎學習24—-使用pymysql連線mysql

sfencs發表於2018-10-22

使用pymysql連線mysql

安裝pymysql

pymysql安裝可以通過兩種方式

使用pip安裝

首先簡單說一下pip的使用方法

獲取幫助
pip --help
升級 pip
pip install -U pip
安裝包
pip install SomePackage
解除安裝包 
pip uninstall SomePackage
升級指定的包
pip install -U SomePackage
搜尋包
pip search SomePackage
檢視指定包的詳細資訊
pip show -f SomePackage
列出已安裝的包
pip freeze or pip list
檢視可升級的包
pip list -o

所以安裝pymysql只需要在cmd中執行pip install pymysql就可以了。

在pycharm中安裝

依次點選[File] >> [settings] >> [Project: python] >> [Project Interpreter] >>+
之後搜尋pymysql點選安裝。

連線mysql

conn=pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="000000",db="db1",charset="utf8")

執行sql語句

cursor = conn.cursor()建立遊標
effect_row = cursor.execute("sql語句") #返回的是受影響的行數
effect_row = cursor.execute("select * from  tb1 where id = %s", (15,)) #使用萬用字元
effect_row = cursor.executemany("insert into tb1(id,name)values(%s,%s)", [(16,"sfencs"),(17,"Tom")])#插入多條資料
conn.commit()#執行有關改變資料庫內容的操作後需要加上,相當於提交資料

獲取相關資料

new_id = cursor.lastrowid#插入語句執行後嗎,獲得該語句的自增id
row_1 = cursor.fetchone()#查詢語句執行後,獲取第一行資料,獲取的資料是元組型別
row_n = cursor.fetchmany(n)#獲取前n行資料((1, `sfencs`), (2, `tom`))
row_all = cursor.fetchall()#獲取所有查詢到的資料

其他

移動遊標

通過移動遊標來fetch想要的資料

cursor.scroll(1,mode=`relative`) # 相對當前位置移動
cursor.scroll(2,mode=`absolute`) # 相對絕對位置移動
改變fetch獲得的資料型別

預設是以元組形式獲得,但也可以改變為字典形式

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#獲得遊標
cursor.execute("select * from tb1")
row_all = cursor.fetchall()#[{`id`: 1, `name`: `sfencs`}, {`id`: 2, `name`: `tom`}, {`id`: 3, `name`: `Jerry`}]

關閉連線

# 關閉遊標
cursor.close()
# 關閉連線
conn.close()

相關文章