# coding=utf-8 import pymysql #连接数据库 db = pymysql.connect(host='127.0.0.1', user='root', password='123456', port=3306) # 使用 cursor() 方法创建一个游标对象 cursor cursor = db.cursor() # 使用 execute() 方法执行 SQL cursor.execute("CREATE DATABASE testdb") #创建数据库testdb cursor.execute("SHOW DATABASES") #查看目前所有的数据 # 以元组类型,返回获取所有记录列表的信息 results = cursor.fetchall() print(results) cursor.execute("USE testdb") #进入数据库testdb cursor.execute("CREATE TABLE testsheet (name VARCHAR(20), sex CHAR(1),age int(2))") #创建名为testsheet的表格 cursor.execute("INSERT INTO testsheet (name,sex,age) VALUES('张三', '男', 22)") #向testsheet表中插入信息 cursor.execute("INSERT INTO testsheet (name,sex,age) VALUES('三二一', '女', 22)") cursor.execute("SELECT * FROM testsheet WHERE name LIKE '%三%'") #从表testsheet中查询名字中有'三'的人的信息 # 以元组类型,返回获取所有记录列表的信息 results = cursor.fetchall() print(results) cursor.execute("DROP TABLE testsheet") #删除表格testsheet cursor.execute("DROP DATABASE testdb") #删除数据库testdb # 提交游标的操作到数据库 db.commit() # 回滚游标所有操作 db.rollback() # 关闭数据库连接 db.close()
python 与数据库交互
猜你喜欢
转载自www.cnblogs.com/testlearn/p/11775829.html
今日推荐
周排行