python3.6中MySQL表的创建和删除

来源:互联网 发布:认识奢侈品的软件 编辑:程序博客网 时间:2024/06/01 10:36
import pymysqlconnect = pymysql.connect(    #连接数据库服务器    user="root",    password="xxxxx",    host="127.0.0.1",    port=3306,    db="MYSQL",    charset="utf8"    )conn = connect.cursor()        #创建操作游标#你需要一个游标 来实现对数据库的操作相当于一条线索#                          查看conn.execute("SELECT * FROM user")    #选择查看自带的user这个表  (若要查看自己的数据库中的表先use XX再查看)rows = conn.fetchall()                #fetchall(): 接收全部的返回结果行,若没有则返回的是表的内容个数 int型for i in rows:    print(i)#                          创建表conn.execute("drop database if exists new_database")   #如果new_database数据库存在则删除conn.execute("create database new_database")   #新创建一个数据库conn.execute("use new_database")         #选择new_database这个数据库# sql 中的内容为创建一个名为new_table的表sql = """create table new_table(id BIGINT,name VARCHAR(20),age INT DEFAULT 1)"""  #()中的参数可以自行设置conn.execute("drop table if exists new_table") # 如果表存在则删除conn.execute(sql)   # 创建表#                           删除# conn.execute("drop table new_table")conn.close()           #   关闭游标连接connect.close()        #   关闭数据库服务器连接 释放内存实现以上代码后进入数据库中查看你会发现多了一个数据库 new_database其中多了一个new_table表

0 0