doctorsong

pymysql

1.增加

import pymysql

#1.连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123123", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

#2.发送命令
cursor.execute("insert into admin(username,password,mobile) values ('xiaoyuyu','qaz123','18300344352')")
conn.commit()

#3.关闭
cursor.close()
conn.close()

 

import pymysql

#1.连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123123", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

#2.发送命令
sql ="insert into admin(username,password,mobile) values (%s,%s,%s)"
cursor.execute(sql,["宋宇","qwe123","18045399911"])
conn.commit()
#3.关闭
cursor.close()
conn.close()
import pymysql

#1.连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123123", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

#2.发送命令
sql = "insert into admin(username,password,mobile) values( %(n1)s, %(n2)s, %(n3)s)"
cursor.execute(sql, {"n1": "集宁", "n2": "qwe123", "n3": "1999999999"})
conn.commit()
#3.关闭
cursor.close()
conn.close()

 2.查

import pymysql

# 1.连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123123", charset="utf8", db="unicom")
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送命令
sql = "select * from admin"
cursor.execute(sql)
data = cursor.fetchall()
for row in data :
    print(row)
# 3.关闭
cursor.close()
conn.close()
import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令( *** 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入***)
cursor.execute("select * from admin where id > %s", [2, ])

# 获取符合条件的第一条数据,字典    None
res = cursor.fetchone()
print(res)  # {'id': 3, 'username': '集宁', 'password': 'qwe123', 'mobile': '1999999999'}

# 3.关闭连接
cursor.close()
conn.close()

3.删除

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令( *** 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入***)
cursor.execute("delete from admin where id=%s", [3, ])
conn.commit()

# 3.关闭
cursor.close()
conn.close()

4.改

import pymysql

# 1.连接MySQL
conn = pymysql.connect(host="127.0.0.1", port=3306, user='root', passwd="root123", charset='utf8', db='unicom')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 2.发送指令( *** 千万不要用字符串格式化去做SQL的拼接,安全隐患SQL注入***)
cursor.execute("update admin set mobile=%s where id=%s", ["1888888888", 4, ])
conn.commit()

# 3.关闭
cursor.close()
conn.close()

 

posted on 2022-10-17 21:59  songyu666  阅读(22)  评论(0编辑  收藏  举报

导航