首先要进行python对数据库的相关连接
以我自己的项目为例:
import pymysql dbhost = 'localhost' dbuser = 'root' dbpass = '123456' dbname = 'db_student' try: db = pymysql.connect(host=dbhost, user=dbuser, password=dbpass, database=dbname) print("数据库连接成功") except pymysql.Error as e: print("数据库连接失败:" + str(e)) cursor = db.cursor()
其次进入数据表的创建
import pymysql dbhost='localhost' dbuser='root' dbpass='123456' dbname='db_student' try: db=pymysql.connect(host=dbhost,user=dbuser,password=dbpass,database=dbname) print("数据库连接成功") except pymysql.Error as e: print("数据库连接失败:"+str(e)) cursor = db.cursor() # 使用execute方法执行SQL语句 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取一条数据 data = cursor.fetchone() print ("Database version : %s " % data) # 如果数据表已经存在使用 execute() 方法删除表。 cursor.execute("DROP TABLE IF EXISTS EMPLOYEE") # 创建数据表SQL语句 create_sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )""" cursor.execute(create_sql) db.close() print("数据库连接关闭!")
再到数据的插入,注意,这里数据的插入是通过终端的输入数据进行的插入
import pymysql dbhost='localhost' dbuser='root' dbpass='123456' dbname='db_student' try: db=pymysql.connect(host=dbhost,user=dbuser,password=dbpass,database=dbname) print("数据库连接成功") except pymysql.Error as e: print("数据库连接失败:"+str(e)) cursor = db.cursor() # 使用execute方法执行SQL语句 cursor.execute("SELECT VERSION()") # 使用 fetchone() 方法获取一条数据 data = cursor.fetchone() print ("Database version : %s " % data) # 如果数据表已经存在使用 execute() 方法删除表。 try: with db.cursor() as cursor: # 准备SQL语句 sql = "INSERT INTO EMPLOYEE (first_name, last_name, age, sex, income) VALUES (%s, %s, %s, %s, %s)" # 初始化一个空列表来保存要插入的数据 data_to_insert = [] # 循环接收用户输入,直到输入'q'退出 while True: first_name = input("请输入名字(输入'q'退出): ") if first_name.lower() == 'q': break last_name = input("请输入姓氏: ") age = input("请输入年龄: ") try: age = int(age) # 尝试将年龄转换为整数 except ValueError: print("年龄必须是整数,请重新输入。") continue sex = input("请输入性别 (M/F): ") income = input("请输入收入: ") try: income = float(income) # 尝试将收入转换为浮点数 except ValueError: print("收入必须是数字,请重新输入。") continue # 将输入的数据添加到列表中 data_to_insert.append((first_name, last_name, age, sex, income)) # 使用executemany()方法执行插入操作 # 检查是否已经有数据需要插入,并执行插入操作 if len(data_to_insert) > 0: with db.cursor() as cursor: # 可以在这里使用with语句来自动关闭游标 cursor.executemany(sql, data_to_insert) db.commit() # 提交事务 # 清空列表以便下次插入 data_to_insert.clear() finally: # 关闭数据库连接 db.close() print("数据已成功保存到数据库中。") print("数据库连接关闭!")
最后的数据查询
import pymysql dbhost = 'localhost' dbuser = 'root' dbpass = '123456' dbname = 'db_student' try: db = pymysql.connect(host=dbhost, user=dbuser, password=dbpass, database=dbname) print("数据库连接成功") except pymysql.Error as e: print("数据库连接失败:" + str(e)) cursor = db.cursor() # 使用参数化查询 select_sql = "SELECT * FROM EMPLOYEE WHERE INCOME " try: cursor.execute(select_sql) results = cursor.fetchall() for row in results: fname = row[0] # 假设第一列是名字 lname = row[1] # 假设第二列是姓氏 age = row[2] # 假设第三列是年龄 sex = row[3] # 假设第四列是性别 income = row[4] # 假设第五列是收入 print("名=%s,姓=%s,年龄=%s,性别=%s,收入=%s" % (fname, lname, age, sex, income)) except pymysql.Error as e: print("Error: unable to fetch data:", e) finally: # 确保数据库连接被关闭 db.close() print("数据库连接关闭!")