python连接mysql操作(1)

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

相关推荐