【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()

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智商不够_熬夜来凑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值