python下操做mysql 之 pymsql

python下操做mysql  之  pymsqlpython

                              pymsql是Python中操做MySQL的模塊,mysql

下載安裝:sql

pip3 install pymysql

使用操做
  1, 執行SQLide

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import pymysql

  

# 建立鏈接

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')

# 建立遊標

cursor = conn.cursor()

  

# 執行SQL,並返回收影響行數

effect_row = cursor.execute("update hosts set host = '1.1.1.2'")

  

# 執行SQL,並返回受影響行數

#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))

  

# 執行SQL,並返回受影響行數

#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

  

  

# 提交,否則沒法保存新建或者修改的數據

conn.commit()

  

# 關閉遊標

cursor.close()

# 關閉鏈接

conn.close()
View Code

  2, 獲取新建立數據自增IDfetch

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import pymysql

  

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')

cursor = conn.cursor()

cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

conn.commit()

cursor.close()

conn.close()

  

# 獲取最新自增ID

new_id = cursor.lastrowid
View Code

  3, 獲取查詢數據spa

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import pymysql

  

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')

cursor = conn.cursor()

cursor.execute("select * from hosts")

  

# 獲取第一行數據

row_1 = cursor.fetchone()

  

# 獲取前n行數據

# row_2 = cursor.fetchmany(3)

# 獲取全部數據

# row_3 = cursor.fetchall()

  

conn.commit()

cursor.close()

conn.close()
View Code

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

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

  4, fetch 數據類型code

#!/usr/bin/env python

# -*- coding:utf-8 -*-

import pymysql

  

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')

  

# 遊標設置爲字典類型

cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

r = cursor.execute("call p1()")

  

result = cursor.fetchone()

  

conn.commit()

cursor.close()

conn.close()
View Code

  5,input 下執行blog

import pymysql
username = input('請輸入用戶名:')

pwd = input('請輸入密碼:')



# 1.鏈接
conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='db8', charset='utf8')


# 2.建立遊標
cursor = conn.cursor()


# 操做
#
# sql = "insert into userinfo(username,pwd) values (%s,%s)"


# effect_row = cursor.execute(sql,(username,pwd))
#同時插入多條數據
#cursor.executemany(sql,[('李四','110'),('王五','119')]) 

# print(effect_row)#

#
# sql = "update userinfo set username = %s  where id = 2"
# effect_row = cursor.execute(sql,username)
# print(effect_row)


#
sql = "delete from userinfo  where id = 2"
effect_row = cursor.execute(sql)
print(effect_row)


#必定記得commit
conn.commit()

# 4.關閉遊標
cursor.close()

# 5.關閉鏈接
conn.close()
View Code
相關文章
相關標籤/搜索