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.基本的な追加、削除、および変更
注:データベースのDML操作には、最後にコミットが必要です。
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)
3.2。更新
# 测试数据
test_table = "py_test"
age = 17
name = "tanshouke"
# 执行SQL
sql = "update py_test set age = '%d' where name = '%s';" %(age, name)
cursor.execute(sql)
# 关闭游标
cursor.close()
db_conn.commit()
# 关闭数据库连接
db_conn.close()
3.3。削除
# 测试数据
test_table = "py_test"
name = "tansk"
# 执行SQL
cursor.execute("delete from py_test where name = '%s';" % name)
# 关闭游标
cursor.close()
db_conn.commit()
# 关闭数据库连接
db_conn.close()
3.4。挿入
# 测试数据
test_table = "py_test"
age = 16
name = "tansk"
# 执行SQL
sql = "insert into py_test(name,age) values('%s', %d);" % (name, age)
cursor.execute(sql)
# 关闭游标
cursor.close()
db_conn.commit()
# 关闭数据库连接
db_conn.close()