赞
踩
pip install mysql-connector-python
-- 创建数据库
create database python_demo DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
-- 创建测试表
create table python_demo.student(
sno int unsigned auto_increment comment '学号',
sname varchar(30) not null comment '姓名',
age int comment '年龄',
birthday date comment '出生日期',
primary key(sno)
) engine=innodb default charset=utf8 comment '学生信息表';
import mysql.connector
# 配置连接信息
conn = mysql.connector.connect(
host='127.0.0.1',
port='3306',
user='root',
password='12345',
database='python_demo'
)
# 当前 mysql 版本号
print(conn.get_server_version())
import mysql.connector from mysql.connector import errorcode try: # 配置连接信息 conn = mysql.connector.connect( host='127.0.0.1', port='3306', user='root', password='12345', database='python_demo' ) # 当前 mysql 版本号 print(conn.get_server_version()) # 捕获异常 except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print('账号或密码错误!') elif err.errno == errorcode.ER_BAD_DB_ERROR: print('数据库不存在!') else: print(err) else: # 关闭连接 conn.close()
目录结构:
config.ini:
[mysql]
host = 127.0.0.1
port = 3306
user = root
password = 12345
database = python_demo
m1.py:
import mysql.connector from mysql.connector import errorcode import configparser # 创建配置解析器对象 config = configparser.ConfigParser() # 读取配置文件 config.read('config.ini') try: # 配置连接信息 conn = mysql.connector.connect( host=config.get('mysql', 'host'), port=config.get('mysql', 'port'), user=config.get('mysql', 'user'), password=config.get('mysql', 'password'), database=config.get('mysql', 'database') ) # 当前 mysql 版本号 print(conn.get_server_version()) # 捕获异常 except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print('账号或密码错误!') elif err.errno == errorcode.ER_BAD_DB_ERROR: print('数据库不存在!') else: print(err) else: # 关闭连接 conn.close()
execute()
:用来执行 sql 语句,如:增删改查,存储过程等commit()
:用来提交事务import mysql.connector # 配置连接信息 conn = mysql.connector.connect( host='127.0.0.1', port='3306', user='root', password='12345', database='python_demo' ) # 创建游标对象 cursor = conn.cursor() # 操作数据:插入、修改、删除 同理,注:数据类型均可用 %s # 操作一条数据 sql = 'insert into student(sname, age, birthday) values(%s, %s, %s);' param = ('张三', '18', '1994-12-08') cursor.execute(sql, param) # 操作多条数据 sql = 'insert into student(sname, age, birthday) values(%s, %s, %s);' param = [('李四', '20', '1992-10-05'), ('王五', '16', '1996-05-26'), ('赵六', '08', '1994-05-26')] cursor.executemany(sql, param) # 提交数据 conn.commit() # 关闭游标和数据库连接 cursor.close() conn.close()
import mysql.connector # 配置连接信息 conn = mysql.connector.connect( host='127.0.0.1', port='3306', user='root', password='12345', database='python_demo' ) # 创建游标对象 cursor = conn.cursor() # 查询数据 sql = 'select sno, sname, age, birthday from student where sno >= %s' param = (1,) cursor.execute(sql, param) result = cursor.fetchall() # 打印结果 for row in result: print(row) # 关闭游标和数据库连接 cursor.close() conn.close()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。