py链接mysql数据库 处理数据

时间:2022-04-18 23:04:19

import pymysql
db = pymysql.connect(‘localhost‘, ‘root‘, ‘root‘, ‘py123‘) # 本机接口,数据库账户,数据库密码,数据库名称
cursor = db.cursor()
# cursor.execute("create database py123")
# data = cursor.fetchone() # 取单条数据
# print(data)
# cursor.execute("drop table if exists newdb_py")


# 创建表结构
sql = """CREATE TABLE Newdb_py1(
stu_id char (8) primary key not null ,
stu_name varchar (20) not null ,
gender char (4) not null ,
register_data Datetime,
phone_number varchar (11))"""
cursor.execute(sql)


# 添加数据
# sql = """INSERT INTO Newdb_py VALUES (
# ‘18301035‘, ‘江勇‘, ‘男‘, ‘2019-10-14 16:20:11‘, ‘15082631486‘
# )"""
# try:
# cursor.execute(sql)
# db.commit() # 提交数据
# except:
# db.rollback() # 回滚


# 查询数据
# sql = """SELECT * FROM Newdb_py"""
# try:
# cursor.execute(sql)
# data = cursor.fetchall()
# for row in data:
# sid = row[0]
# name = row[1]
# sex = row[2]
# data = row[3]
# phone = row[4]
# print("id:{} name:{} sex:{} phone:{}".format(sid, name, sex, phone)) # 显示数据
# except:
# print("ERROR")
#
db.close()