python利用pymysql连接数据库进行创建数据表,一次性插入多条数据数据,查询数据

首先要进行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("数据库连接关闭!")
  • 9
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,这是一个技术问题,我可以为您解答。 首先,在Python中可以使用pymysql库来实现与MySQL数据库的交互。您需要先安装pymysql库,并且需要有一个MySQL数据库实例。 插入数据的代码示例: ```python import pymysql # 连接数据库,修改参数为您的数据库连接信息 conn = pymysql.connect(host='localhost', port=3306, user='root', password='yourpassword', db='yourdb') # 获取操作游标 cursor = conn.cursor() # 实现插入操作 sql = "INSERT INTO yourtable (column1, column2, column3) VALUES (%s, %s, %s)" values = ('value1', 'value2', 'value3') cursor.execute(sql, values) # 提交数据 conn.commit() # 关闭游标和数据库连接 cursor.close() conn.close() ``` 查询数据的代码示例: ```python import pymysql # 连接数据库,修改参数为您的数据库连接信息 conn = pymysql.connect(host='localhost', port=3306, user='root', password='yourpassword', db='yourdb') # 获取操作游标 cursor = conn.cursor() # 实现查询操作 sql = "SELECT * FROM yourtable" cursor.execute(sql) # 获取查询结果 result = cursor.fetchall() for row in result: print(row) # 关闭游标和数据库连接 cursor.close() conn.close() ``` 需要注意的是,您需要将代码中的`yourtable`、`column1`、`column2`、`column3`、`value1`、`value2`、`value3`修改为您实际使用的表名和字段名,以及需要插入的具体值。同时,需要将代码中的`localhost`、`3306`、`root`、`yourpassword`、`yourdb`修改为您实际使用的MySQL数据库连接信息。 希望对您有所帮助。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值