博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

python操作MySQL

Posted on 2023-08-10 17:42  steve.z  阅读(35)  评论(0编辑  收藏  举报

# macOS 操作 MySQL 服务

# 启动MySQL
mysql.server start

# 停止MySQL
mysql.server stop

# 重启 MySQL
mysql.server restart

# 查看当前 MySQL 服务状态
mysql.server status

# 配置 MySQL 服务器
# 我们需要运行以下脚本配置 MySQL 服务器的安全性:
mysql_secure_installation


# 链接 MySQL 
mysql -uroot -p
# 密码:12345678


# 常用 MySQL 命令
# show databases;
# use databasename;
# show tables;
# exit;


# MySQL 图形化管理工具 DBeaver


# MySQL 服务器管理命令
# brew 提供了实用的命令可以管理 MySQL 服务器。
# brew services start mysql: 启动 MySQL 服务器,并设置为自启动。
# brew services stop mysql: 停止 MySQL 服务器,并设置为不自启动。
# brew services run mysql: 只启动 MySQL 服务器。
# mysql.server start: 启动 MySQL 服务器。
# mysql.server stop: 停止 MySQL 服务器。

# mysql 
show databases;

use mysql;

show tables;

select * from func;

-- 注释内容
# 注释内容
/*
	注释内容
*/


/* 选中某句 SQL 语句,按 control + 回车 执行该条语句 */


-- 字符串使用单引号


create database test charset utf8;
show databases;
drop database xxx;

select database();

show tables;

CREATE TABLE STUDENTS (
	sid int,
	name varchar(50),
	age int
);

drop table students;

-- 只查看返回的前 5 条数据
SELECT * FROM students order by age DESC limit 5;

-- 查看跳过前 10 条,然后查看接下来的 5 条数据
SELECT * FROM students order by age DESC limit 10, 5;




Python 语言操作 MySQL 数据库

先通过执行 bash 命令$ pip3 install pymysql 安装库


#
#   py_mysql.py
#   py_learn
#
#   Created by Z. Steve on 2023/8/10 16:57.
#


# 通过 pymysql 库来操作 MySQL 数据库

from pymysql import Connection

# 1. 创建连接对象
conn = Connection(host="localhost", port=3306, user="root", password="12345678")
# 输出 MySQL 数据库信息
print(conn.get_server_info())

# 2. 执行相关操作
# 2.1 通过连接对象, 获取游标对象
cursor = conn.cursor()
# 2.2 通过连接对象, 选择数据库
conn.select_db("sys")
# 2.3 通过游标对象, 执行 SQL
# cursor.execute("create table students(sid int, sname varchar(50), age int);")
cursor.execute("select * from students;")
# results 是一个元组对象, 该对象中的每个元素又是一个元组对象
results = cursor.fetchall()
# 循环遍历
for item in results:
    print(item)
print(results)
print("sql 语句执行成功!")

# 关闭数据库连接
conn.close()






执行 insert、update 等更改数据的行为时, 需要进行 commit

#
#   py_mysql_insert.py
#   py_learn
#
#   Created by Z. Steve on 2023/8/10 17:33.
#

from pymysql import Connection

conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="12345678"
)

cursor = conn.cursor()
conn.select_db("sys")

# 通过 cursor 对象执行SQL
cursor.execute("insert into students(sid, sname, age) values(1007, '王孙', 24);")
# 通过 conn 对象提交执行(提交事务)
conn.commit()

conn.close()




# 注意:可通过创建 Connection() 对象时, 指定参数来实现自动提交
'''
conn = Connection(
    host="localhost",
    port=3306,
    user="root",
    password="12345678",
    autocommit=True
)
'''

参考地址

https://www.sjkjc.com/mysql/install-on-macos/