Python基础-MySQL的安装和运行
来源:互联网 发布:知乎 发现 编辑:程序博客网 时间:2024/05/17 19:56
MySQL是Web世界中使用最广泛的数据库服务器。SQLite的特点是轻量级、可嵌入,但不能承受高并发访问,适合桌面和移动应用。而MySQL是为服务器端设计的数据库,能承受高并发访问,同时占用的内存也远远大于SQLite。
安装 MySQL 软件
下载
下载地址 mysql-5.6.24-win32.zip
https://dev.mysql.com/downloads/mysql/
解压并配置环境变量
例如我的MySQL的bin文件的存放的路径如下
D:\mysql-5.6.24-win32\bin
如下图配置,右键我的电脑->属性->高级系统配置->环境变量
管理员 cmd 窗口
不然会有如下报错
Install/Remove of the Service Denied!
安装MySQL服务
imysqld -install
C:\WINDOWS\system32>mysqld -installService successfully installed.
启动 MySQL 服务
net start mysql
C:\WINDOWS\system32>net start mysqlMySQL 服务正在启动 ..MySQL 服务已经启动成功。
其中默认连接数据库名为“root”,密码为空
安装MySQL驱动
pip install mysql-connector-python –allow-external mysql-connector-python
安装过程如下
D:\PythonProject>pip install mysql-connector-python --allow-external mysql-connector-pythonDEPRECATION: --allow-external has been deprecated and will be removed in the future. Due to changes in the repository protocol, it no longer has any effect.Collecting mysql-connector-python Downloading mysql_connector_python-8.0.5-py2.py3-none-any.whl (249kB) 100% |████████████████████████████████| 256kB 18kB/sInstalling collected packages: mysql-connector-pythonSuccessfully installed mysql-connector-python-8.0.5
运行一个用例
运行代码
#!/usr/bin/env python3# -*- coding: utf-8 -*-# Python基础 连接到MySQL服务器import mysql.connector# 注意把password设为你的root口令conn = mysql.connector.connect(user='root', password='', database='test')cursor = conn.cursor()# 创建user表cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')# 插入一行记录,注意MySQL的占位符是%scursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'LiBai'])cursor.rowcount# 提交事务conn.commit()# 运行查询cursor.execute('select * from user where id = %s', ('1',))values = cursor.fetchall()print(values)cursor.close()conn.close()
运行结果
D:\PythonProject>python main.py[('1', 'LiBai')]
阅读全文