一、pymysql模块安装
pip3 install pymysql
二、连接数据库
2.1、创建测试数据
mysql> create database AA;
mysql> use AA
mysql> create table test(id int primary key auto_increment,name varchar(25),passwd varchar(25));
mysql> insert into test(name,passwd) values('AA',123),('BB',456),('CC',789);
mysql> select * from test;
+----+------+--------+
| id | name | passwd |
+----+------+--------+
| 1 | AA | 123 |
| 2 | BB | 456 |
| 3 | CC | 789 |
+----+------+--------+
3 rows in set (0.00 sec)
2.2、连接数据库
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pymysql
user=input("用户名:").strip()
pwd=input("密码:").strip()
#连接
conn = pymysql.connect(host="10.0.0.12",port=3306,user="root",passwd="mysql",db="AA")
#游标
cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示
# cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) #以字典形式返回
#执行sql语句
sql = 'select * from AA.test where name="%s" and passwd="%s"' %(user,pwd) #注意%s需要加引号
print(sql)
res=cursor.execute(sql) #执行sql语句,返回sql查询成功的记录数目
print(res)
#关闭游标及连接
cursor.close()
conn.close()
if res:
print("登录成功")
else:
print("登录失败")