关于Python连接MySQL

关于Python连接MySQL

1、下载Connector/Python 8.0.13。mysql-connector-python-8.0.13-py3.7-windows-x86-64bit.msi。
https://dev.mysql.com/downloads/connector/python/

2、如果没有安装.NET环境,安装Connector/Python 8.0.13,会出现提示This application requires Visual Studio 2015 Redistributable,此时需要安装vc_redist.x64.exe。https://www.microsoft.com/zh-cn/download/details.aspx?id=48145

4、建立数据库以及测试表。

drop database test;
create database test;
use test;
create table app_users (
user_id int(12) auto_increment,
user_code varchar(60) not null,
user_name varchar(256) null,
primary key(user_id)
);
insert into app_users(user_code, user_name) values('9001', 'jzh');
insert into app_users(user_code, user_name) values('9002', 'chanpinxue.cn');
insert into app_users(user_code, user_name) values('9003', 'chanpinxue.cn');

5、测试代码。

#coding=utf-8

import mysql.connector                 

# 测试MySQL
try:
    conn = mysql.connector.connect(host='127.0.0.1',port='3306',  user='root', password='root', database='test', charset='utf8')
except mysql.connector.Error as e:
    print('连接失败{}'.format(e))

cursor = conn.cursor()
try:
    # 插入
    cursor.execute('insert into app_users (user_code, user_name) values (%s, %s)', ['9004', 'jiangzhihao'])
    cursor.rowcount
    # 提交事务
    conn.commit()

    # 更新
    cursor.execute('update app_users set user_name = %s where user_code = %s', ['jiangzhihao2018', '9003'])
    cursor.rowcount
    # 提交事务
    conn.commit()

    # 查询
    sql_query = 'select user_code, user_name from app_users'
    cursor.execute(sql_query)
    for user_code, user_name in cursor:
        print(user_code, user_name)

except mysql.connector.Error as e:
    print('查询失败{}'.format(e))
finally:
    cursor.close()
    conn.close()

 

 

 

发表回复

您的电子邮箱地址不会被公开。