当前位置:Gxlcms > 数据库问题 > python3连接mysql数据库

python3连接mysql数据库

时间:2021-07-01 10:21:17 帮助过:27人阅读

主键自增, username VARCHAR(255) comment 用户名, passwd VARCHAR(255) COMMENT 密码 )ENGINE=INNODB charset=utf8

2.准备配置文件:

[mysql]
host = localhost
user = root
passwd = root
database = python

3.获取mysql连接信息:

import pymysql
import configparser
import logging.config

conf = configparser.ConfigParser()
conf.read("prod.conf")

# 获取 mysql 连接信息
host = conf.get("mysql", "host")
user = conf.get("mysql", "user")
passwd = conf.get("mysql", "passwd")
database = conf.get("mysql", "database")

4.编写连接方法:

def mysqlConnection():
    try:
        connect = pymysql.connect(host, user, passwd, database)
        logging.debug("成功连接mysql")
        return connect
    except Exception as e:
        logging.error(repr(e))
        return None

5.main方法中执行sql:

if __name__ == ‘__main__‘:
# 连接
conn = mysqlConnection()
# 获取游标
cursor = conn.cursor()
sql = ‘insert into users(username,passwd) values("zhangsan","123456")‘
cursor.execute(sql)
conn.commit()
print("成功插入数据库")
# 关闭连接
conn.close()

6.运行之后查看数据库

技术分享图片

技术分享图片

 

7.测试其他的方法:

技术分享图片

8.完整代码:

import pymysql
import configparser
import logging.config

conf = configparser.ConfigParser()
conf.read("prod.conf")

# 获取 mysql 连接信息
host = conf.get("mysql", "host")
user = conf.get("mysql", "user")
passwd = conf.get("mysql", "passwd")
database = conf.get("mysql", "database")


def mysqlConnection():
    try:
        connect = pymysql.connect(host, user, passwd, database)
        logging.debug("成功连接mysql")
        return connect
    except Exception as e:
        logging.error(repr(e))
        return None


if __name__ == __main__:
    # 连接
    conn = mysqlConnection()
    # 获取游标
    cursor = conn.cursor()
    """
    sql = ‘insert into users(username,passwd) values("zhangsan","123456")‘
    cursor.execute(sql)
    conn.commit()
    print("成功插入数据库")
    """
    sql2 = select * from users
    cursor.execute(sql2)
    print("表中共有数据:" + str(cursor.rowcount) + "")
    result = cursor.fetchall()
    print(result)
    # 关闭连接
    conn.close()

 

python3连接mysql数据库

标签:执行sql   pass   port   获取   err   logging   parser   username   innodb   

人气教程排行