1.前期准备
1.1.数据库建库
create database py_test DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
1.2.数据库建表
create table py_test ( id int primary key auto_increment, name varchar(50) not null, age int(10) )character set = utf8;
insert into py_test(name,age) values(‘tansk‘,20);
insert into py_test(name,age) values(‘tanshouke‘,18);
1.3.放行服务器防火墙
systemctl stop firewalld
1.4.开放连接权限
grant all privileges on *.* to ‘root‘@‘%‘ identified by ‘123456‘;
grant all privileges on *.* to ‘root‘@‘localhost‘ identified by ‘123456‘;
flush privileges;
2.数据库连接
2.1.创建数据库连接
import pymysql
class DbUtil(object):
def __init__(self):
self.get_conn()
def get_conn(self):
# 打开数据库连接
try:
conn = pymysql.connect(
host="192.168.247.13",
port=3306,
user="root",
password="123456",
database="py_test"
)
except Exception as e:
print("数据库连接报错: %s " % e)
finally:
print("数据库连接: ")
print(conn)
print("连接类型: ")
print(type(conn))
print("")
return conn
if __name__ == ‘__main__‘:
getconn = DbUtil.get_conn(self=True)
3.基础的增删改查
3.1.查询
写一个简单的查询语句,实现python与mysql数据库交互
import tansk_01_数据库连接 as DbConn
# 连接数据库
db_conn = DbConn.DbUtil.get_conn(self=True)
# 获取游标
cursor = db_conn.cursor()
# 测试数据库表
test_table = "py_test"
# 执行SQL
cursor.execute("select * from % s;" % test_table)
# 轮询取值
while 1:
results = cursor.fetchone()
if results is None:
# 表示取完结果集
break
print(results)
# 关闭游标
cursor.close()
# 关闭数据库连接
db_conn.close()
运行结果:
数据库连接:
<pymysql.connections.Connection object at 0x00000268A0B7A6D0>
连接类型:
<class ‘pymysql.connections.Connection‘>
(1, ‘tansk‘, 20)
(2, ‘tanshouke‘, 18)