python连接mysql操作(1)

走远了吗. 提交于 2019-12-03 20:07:07

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

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!