python连接mysql操作

Posted bjx2020

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python连接mysql操作相关的知识,希望对你有一定的参考价值。

python连接mysql操作(1)

import pymysql
import pymysql.cursors

# 连接数据库
connect = pymysql.Connect(
    host=10.10.146.28,
    port=3306,
    user=admin_m,
    passwd=fcfmTbRw1tz2x5L5GvjJ,
    db=test,
    charset=utf8mb4
)


def create_table():
    cursor = connect.cursor()

    # 使用execute()方法执行SQL,如果表存在就删除
    cursor.execute("drop table if exists employee")

    # 使用预处理器语句创建表
    sql ="""CREATE TABLE employee(
    id int not null auto_increment,
    first_name varchar(20) not null,
    last_name varchar(20) not null,
    age int not null default 0,
    sex int not null default ‘0‘,
    income decimal not null default 0.00,
    create_time datetime,
    primary key(id)
    ) Engine=InnoDB DEFAULT CHARSET=utf8mb4 comment="员工表"
    """

    try:
        cursor.execute(sql)
        print("CREATE TABLE employee success.")
    except Exception as e:
        print("CREATE TABLE employee failed, CASE:%s" % e)
    finally:
        cursor.close()
        # 关闭数据库连接
def main():
    create_table()

if __name__ == "__main__":
    main()

 

以上是关于python连接mysql操作的主要内容,如果未能解决你的问题,请参考以下文章