当前位置:Gxlcms > 数据库问题 > mysql python pymysql模块 基本使用

mysql python pymysql模块 基本使用

时间:2021-07-01 10:21:17 帮助过:11人阅读

这就用到了pymysql模块,该模块本质就是一个套接字客户端软件,使用前需要事先安装

pip3 install pymysql

 

mysql 服务端ip = 192.168.0.106

我自己电脑 192.168.0.105

 

创建数据库db10

mysql> create database db10 charset=utf8;
Query OK, 1 row affected (0.12 sec)

 

use db10;

 

创建表

mysql> create table userinfo(id int not null primary key auto_increment,name varchar(50) not null,pwd varchar(50) nott null);
Query OK, 0 rows affected (0.39 sec)

 

插入表

mysql> insert into userinfo(name,pwd) values(mike,123),(jack,456);
Query OK, 2 rows affected (0.19 sec)
Records: 2  Duplicates: 0  Warnings: 0

 

用户信息表创建好了

mysql> select * from userinfo;
+----+------+-----+
| id | name | pwd |
+----+------+-----+
|  1 | mike | 123 |
|  2 | jack | 456 |
+----+------+-----+
2 rows in set (0.00 sec)

 

授权

mysql> grant all on *.* to root@192.168.0.105 identified by 123;
Query OK, 0 rows affected (0.15 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

 

游标就是登录进入mysql的命令行的光标

游标是给mysql提交命令的接口

mysql> 

 

 

# 拿到游标对象
cur = conn.cursor()


游标是给mysql提交命令的接口
mysql>
把sql语句传递到这里



rows = cur.execute(sql)
execute拿到结果 不是 我mysql查询的结果,而是

红色 2 的结果 代表拿到2行结果
select * from userinfo;
+----+------+-----+
| id | name | pwd |
+----+------+-----+
|  1 | mike | 123 |
|  2 | jack | 456 |
+----+------+-----+
2 rows in set (0.00 sec)

如果绿色的值 不为0 代表 我输入的账号和密码都输入正确了

 

执行完sql语句要关闭游标和mysql连接

 

完整代码

 

 

import pymysql

input_user = input(usr>>>:).strip()
input_pwd = input(pwd>>>:).strip()

mysql_host = 192.168.0.106
port = 3306
mysql_user = root
mysql_pwd = 123
encoding = utf8

# 建立 连接mysql服务端

conn = pymysql.connect(
    host=mysql_host,  # mysql服务端ip
    port=port,  # mysql端口
    user=mysql_user,  # mysql 账号
    password=mysql_pwd,  # mysql服务端密码
    db=db10,  # 操作的库
    charset=encoding  # 读取字符串编码

)

# 拿到游标对象
cur = conn.cursor()

‘‘‘
游标是给mysql提交命令的接口
mysql> 
把sql语句传递到这里
‘‘‘



# 执行sql语句
‘‘‘
    执行sql语句之前应该根据我输入的用户名和密码,到数据库里面的表里
    查有没有我输入的用户名和密码
    
‘‘‘
# 写一条sql语句往后台去查
# 注意%s需要加引号
sql= select * from userinfo where name="%s" and pwd="%s"; %(input_user,
                                                            input_pwd)

‘‘‘
    如果这条sql语句能够查出结果,我输入的账号和密码,数据库是存在的
    证明我输入的账号和密码是对的
    如果执行sql语句 没有结果就是数据库没有我输入的账号和密码
‘‘‘

# 把sql语句传给游标执行
rows = cur.execute(sql) # #执行sql语句,返回sql查询成功的记录数目

# 执行完sql语句要关闭游标和mysql连接
cur.close()
conn.close()

# 进行判断
if rows:
    print("登录成功")
else:
    print("登录失败")

‘‘‘
usr>>>:xxx
pwd>>>:123
登录失败
‘‘‘

‘‘‘
usr>>>:mike
pwd>>>:123
登录成功
‘‘‘

 

 

 

 

如果mysql部署在centos 记得把 iptables 加上

-A INPUT -m state --state NEW -m tcp -p tcp --dport 3306 -j ACCEPT

还有selinux 关掉

mysql python pymysql模块 基本使用

标签:sql查询   nbsp   value   cep   inpu   判断   需要   into   数据   

人气教程排行