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
相关文章
相关标签/搜索