import mysql.connector
####### 数据库配置信息
mydb = mysql.connector.connect(
host=“10.10.10.10”,
port=‘3306’,
user=“vivian”,
passwd=“123456”,
database=“vivian”
)
#连接数据库
mycursor = mydb.cursor()
#创建数据库
#mycursor.execute(“create database if not exists vivian”)
#查看所有表
#mycursor.execute(“show tables;”)
#for x in mycursor:
####### print(x)
#删除表中数据
#mycursor.execute(“delete from demowhere mobile=‘18600001234’;”)
#mycursor.execute(“delete from demo;”)
#创建表
mycursor.execute(“create table if not exists demo (name varchar(255), email varchar(255),mobile varchar(255));”)
#插入数据
sql = “insert into demo (name, email ,mobile) values(%s, %s, %s)”
val = (“vivian”, “zhengq@tjipr.com”,“18600001234”)
try:
######## 执行sql语句
mycursor.execute(sql, val)
####### 执行sql语句
mydb.commit()
except:
####### 发生错误时回滚
mydb.rollback()
####### 打印插入数量
#print(mycursor.rowcount, “Records inserted”)
#查看表数据
mycursor.execute(“select * from demo;”)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
####### 关闭数据库连接
mydb.close()