python中的mysql数据库操作

参考:https://www.cnblogs.com/fnng/p/6863616.html

 

安装MySQL,创建数据库和表

 

db_fixture\db_config.ini

[mysqlconf]
host=127.0.0.1
port=3306
user=root
password=123456
db_name=guest_test

如果.ini文件创建不了,参考:https://blog.csdn.net/github_38996697/article/details/88998626

安装相应插件

 

mysql_db.py

from pymysql import connect, cursors
from pymysql.err import OperationalError
import os
import configparser as cparser

# =================读取db_config.ini文件设置======
# os.path.dirname(path) 去掉文件名,返回目录
# os.path.dirname(__file__) 以完整路径被运行的,输出该脚本所在的完整路径
#                           以相对路径被运行的, 那么将输出空目录
base_dir = str(os.path.dirname(os.path.dirname(__file__)))
base_dir = base_dir.replace(\\,/)
file_path = base_dir + "/db_config.ini"

# ConfigParser专门针对db_config.ini内容的文件格式使用的
# https://www.cnblogs.com/yrash/p/11319357.html
cf = cparser.ConfigParser()
cf.read(file_path)

host = cf.get("mysqlconf","host")  # get方法Section下的key对应的value
port = cf.get("mysqlconf","port")
db = cf.get("mysqlconf","db_name")
user = cf.get("mysqlconf","name")
password = cf.get("mysqlconf","password")


# 连接MySQL数据库
connection = pymysql.connect(host=host,
                             user=user,
                             password=password,
                             db=db,
                             charset=utf8mb4,
                             cursorsclass=cursors.DictCursor)

# 通过cursor创建游标
cursor = connection.cursor()

# 插入语句
sql = "INSERT INTO `users` (`email`, `password`) VALUES (‘huzhiheng@itest.info‘, ‘123456‘)"
cursor.execute(sql)

# 提交SQL
connection.commit()

# ===============查询==============

# 执行数据查询
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=‘huzhiheng@itest.info‘"
cursor.execute(sql)

#查询数据库单条数据
result = cursor.fetchone()
print(result)

print("-----------华丽分割线------------")

# 执行数据查询
sql = "SELECT `id`, `password` FROM `users`"
cursor.execute(sql)

#查询数据库多条数据
result = cursor.fetchall()
for data in result:
    print(data)


# 关闭数据连接
connection.close()

host为数据库的主机IP地址,portMySQL的默认端口号,user为数据的用户名,password为数据库的登录密码,db为数据库的名称。

  cursor()方法创建数据库游标。

  execute()方法执行SQL语句。

  commit()将数据库的操作真正的提交到数据。

  fetchone() 用于查询单条数据。

  fetchall() 用于查询多条数据。

 

  close() 最后不要忘记了关闭数据连接。

 

python中的mysql数据库操作

上一篇:mysql的内连接,左连接,右连接(文章属于转载哈,转载后整理部分内容)


下一篇:数据库三范式