gpt4 book ai didi

python - 如何使用 Python 3 在 MySQL 中存储信息?

转载 作者:行者123 更新时间:2023-11-29 18:34:18 25 4
gpt4 key购买 nike

我想存储简单的信息,比如使用 python 在 mysql 表中存储数字。我将 MySQL 本地服务器链接到 PyCharm,但我只是不知道如何编写代码以将信息存储在表中。我想使用一些简单的“if”并将打印结果立即存储在某个表中。

我该怎么做?

谢谢!对于初学者来说,如果我只能存储价格,那就太好了。我的一段代码:

    running = True

while running:
try:
buget = int(input("Money: "))
except ValueError:
print("Please enter your buget using only numbers!")
continue
else:
print("Continue to the next step.")
break

class Cars:
def __init__(self,model,consumption,price,transmision):
self.model = model
self.consumption = consumption
self.price = price
self.transmision = transmision
self.combination = model + " " + price

car_1 = Cars("BMW", "7%", "20000", ["Manual"])
car_2 = Cars("Audi", "8%", "30000 euro", ["Automated"])
car = (car_1, car_2)

for masini in car:
guess = str(input("What car would you like? ").capitalize())
if guess == "Bmw" and buget >= 20000:
print("-----------------")
print(car_1.model)
print(car_1.consumption)
print(car_1.price)
print(",".join(car_1.transmision))
print(car_1.combination)
elif guess == "Audi" and buget >= 30000:
print("-----------------")
print(car_2.model)
print(car_2.consumption)
print(car_2.price)
print(",".join(car_2.transmision))
print(car_2.combination)
elif guess == "Bmw" and buget < 20000:
print("You can't afford this car.")
elif guess == "Audi" and buget < 30000:
print("You can't afford this car.")
elif guess is not "Audi" and buget < 30000:
print("This car doesn't exist!")
elif guess is not "Bmw" and buget < 20000:
print("This car doesn't exist.")
else:
print("This car is unavailable!")
break

最佳答案

首先,您需要一个处理连接的驱动程序。广泛使用的一个称为:MySQLdb,您可以使用 pip 或手动安装它:

pip install MySQL-python

获得模块后,您可以通过以下方式连接到数据库:

db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

确保您已使用 import MySQLdb 导入了脚本顶部的模块。之后,您就可以开始使用数据库了。看一个非常好的教程here .

也看看here也是如此。

关于python - 如何使用 Python 3 在 MySQL 中存储信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45434869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com