pymysql安装

pip install pymysql

链接数据库、执行sql、关闭连接

import pymysql
user = input('请输入用户名请输入密码:').strip()
pwd= input("请输入密码:").strip()

# 建立连接
conn = pymysql.connect(
    host = '192.168.1.1',
    port = '3306',
    user = 'root',
    password = '123',
    db = 'myTestDB',
    charset = 'utf8',
)

# 获取游标
cursor = conn.cursor()

# 执行sql语句
# sql = 'select * from USER_TABLE where user="%s" and pwd=%s' % (user,pwd) 自己拼接sql语句有安全风险
# rows = cursor.excute(sql)
sql = 'select * from USER_TABLE where user="%s" and pwd=%s'
rows = cursor.excute(sql,(user,pwd))

cursor.close()
conn.close()

if rows:
    print("登录成功")
else:
    print("登录失败")

增删改查操作

插入数据

import pymysql
user = input('请输入用户名请输入密码:').strip()
pwd= input("请输入密码:").strip()

# 建立连接
conn = pymysql.connect(
    host = '192.168.1.1',
    port = '3306',
    user = 'root',
    password = '123',
    db = 'myTestDB',
    charset = 'utf8',
)

# 获取游标
cursor = conn.cursor()


sql = 'insert into USER_TABLE(user,pwd) values(%s,%s)'

# 插入单个数据
rows1 = cursor.excute(sql,(user,pwd))

# 插入多个数据
rows2 = cursor.excutemany(sql,[(user,pwd),('aaa','123'),('bbb','123')])
# 查看插入之前的数据库数量
print(cursor.lastrowid)
conn.commit()
cursor.close()
conn.close()

查找数据

import pymysql
user = input('请输入用户名请输入密码:').strip()
pwd= input("请输入密码:").strip()

# 建立连接
conn = pymysql.connect(
    host = '192.168.1.1',
    port = '3306',
    user = 'root',
    password = '123',
    db = 'myTestDB',
    charset = 'utf8',
)

# 获取游标
cursor = conn.cursor()

sql = 'select * from USER_TABLE;'
# 查询
rows  = cursor.excte(sql)

# 取单个数据
single_data = cursor.fetchone()
# 取多个数据
multiple_data = cursor.fetchmany(2)
# 取出所有数据
all_data = cursor.fetchall()
# scroll 绝对位置移动
cursor.scroll(3,mode='absolute')
# scroll 相对位置移动
cursor.scroll(3,mode='relative')

conn.commit()
cursor.close()
conn.close()
内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!