python学习笔记之使用PyCharm连接mysql数据库

Posted 智商不够_熬夜来凑

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python学习笔记之使用PyCharm连接mysql数据库相关的知识,希望对你有一定的参考价值。

代码:

# coding:utf-8

'''
 mysql search join
'''

import mysql.connector

config = 
    'host': 'localhost',
    'port': 3306,
    'user': 'root',
    'password': 'che88888',
    'database': 'test'

con = mysql.connector.connect(**config)

# 创建游标

cursor = con.cursor(buffered=True)

sql = "select e.name,e.uid,d.address from user e join userInfo d on e.uid = d.user_id"

try:
    con.start_transaction()
    cursor.execute(sql)
    con.commit()
    # 打印
    for val in cursor:
        print(val)
except Exception as e:
    print(e)
    con.rollback()
finally:
    if 'con' in dir():
        con.close()

连接池:

# coding:utf-8

import mysql.connector.pooling

config = 
    'host': 'localhost',
    'port': 3306,
    'user': 'root',
    'password': 'che8888',
    'database': 'test'


try:
    pool = mysql.connector.pooling.MySQLConnectionPool(
        **config,
        pool_size=10
    )
    con = pool.get_connection()
    con.start_transaction()
    cursor = con.cursor()
    sql = "select name from user"
    cursor.execute(sql)
    for val in cursor:
        print(val)
    con.commit()
except Exception as e:
    if "con" in dir():
        con.rollback()
    print(e)

循环执行sql语句

# coding: utf-8

import mysql.connector.pooling

config = 
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "che88888",
    "database": "test"

try:
    pool = mysql.connector.pooling.MySQLConnectionPool(
        **config,
        pool_size=10
    )

    con = pool.get_connection()

    cursor = con.cursor()
    # 插入
    sql = "insert into user(id,name) values(%s,%s)"
    data = [[21, '张三'], [32, '里斯'], [22, '王二'], [23, '熊大']]
    cursor.executemany(sql, data)

    # 查询
    msql = "select * from user"
    cursor.execute(msql)
    for val in cursor:
        print(val)
except Exception as e:
    print(e)
    if "con" in dir():
        con.rollback()

 

以上是关于python学习笔记之使用PyCharm连接mysql数据库的主要内容,如果未能解决你的问题,请参考以下文章

Python学习笔记之循环结构

Python 学习笔记-00学习方法-环境安装篇-pycharm 安装和使用

Python学习笔记之字典和集合

Python学习笔记之运算符

Python学习笔记之列表和元组

Python 学习笔记之字符串