Python-pymysql

一 安裝及導入mysql

  1. pip3 install pymysqlsql

  2. 安裝完須要把包的路徑加到Pycharm的路徑中安全

二 執行SQL語句fetch

import pymysql

# create connection
connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test', charset="utf8") # create cursor cursor = connection.cursor() # execute statement cursor.execute('insert into tb1(nid,name) values(3, "Howard")') #cursor.execute('insert into tb1(nid,name) values(4, %s), input') 能夠進行字符串拼接傳參數,不能經過字符串拼接後傳遞變量的形式,不安全

#execute many statements
value = ( (5,'Paul'), (6, 'Wade') )
cursor.executemany('insert into tb1
(nid,name) values(%s,%s), value)
# commit statemnet connection.commit() 
# display info 不用commit
cursor.execute('select * from tb1')
result = cursor.fetchall()
#result = cursor.fetchone()
#result = cursor.fetchmany(size)
print(result)
# close cursor
cursor.close()
# close connection connection.close()

  執行插入語句後的結果:spa

    

  在fetch數據時按照順序進行,可使用cursor.scroll(num,mode)來移動遊標位置,如:code

  • cursor.scroll(1,mode='relative')  # 相對當前位置移動一行
  • cursor.scroll(1,mode='absolute') # 相對絕對位置移動一 行

   b. 另外一種建立cursorblog

 1 import pymysql
 2 
 3 # create connection
 4 connection = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='test', charset="utf8")
 5 
 6 # create cursor
 7 #cursor = connection.cursor()
 8 cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
 9 # execute statement
10 cursor.execute('select * from tb1') #返回值是受影響的行數
11 print(cursor.fetchall())
12 #commit statemnet
13 # connection.commit()
14 
15 #close connection
16 connection.close()

  執行結果:ip

  

 

   能夠看出是字典,這樣就能夠經過key, value的形式拿到每個值了,比元祖更好用。字符串

  c.獲取新建立的自增ID input

id = cursor.lastrowid() #拿最後一條的id
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息