在python中使用pymysql连接数据库

# 导入pymysql
import pymysql

# 连接服务端
conn = pymysql.connect(
    host = '127.0.0.1',     # MySQL地址
    port = 3306,     # MySQL端口
    user = 'root',     # MySQL用户名
    password = '123',     #MySQL密码
    db = 'test',     # 选库
    charset = 'utf8',     # 设置字符编码
    autocommit = True     # 设置增删改后自动提交
)

# 创建游标,并设置返回值为字典
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

#用户输入
user_name = input('user_name:').strip()
pwd = input('pwd:').strip()

# 拼接sql语句
sql = 'select * from user_info where name=%s and pwd=%s'

# 执行sql语句
cursor.execute(sql,(user_name,pwd))

# 接收返回值
data = cursor.fetchone()

# 判断返回值
if data:
    print('登录成功')
else:
    print('登录失败')

猜你喜欢

转载自www.cnblogs.com/hellozizi/p/11401085.html