2017-08-01 45 views
0

我想存儲簡單的信息,如使用python的mysql表中的數字。 我將我的MySQL本地服務器連接到PyCharm,我只是不知道如何編寫代碼以便將信息存儲在表中。 我正在考慮使用一些簡單的「if」,並將打印結果立刻存儲在某個表中。如何使用Python 3將信息存儲在MySQL中?

我該怎麼做?

謝謝! 對於初學者來說,如果我只能存儲價格,那就太棒了。 海賊王我的代碼:

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 
+0

SO不是關於關係數據庫和python db-api的衆多在線教程的替代品。 –

+0

查看pymysql庫,並使用與打印語句類似的for循環執行它,或者將它放入熊貓數據框並在其上運行'pandas.to_sql'。 – cardamom

+0

[我如何在Python中連接MySQL數據庫?](https://stackoverflow.com/questions/372885/how-do-i-connect-to-a-mysql-database-in-python) –

回答

0

首先,你需要它處理你的連接的驅動程序。其中一個被廣泛使用的稱爲:MySQLdb你可以用PIP或手動安裝:

pip install MySQL-python 

之後,你有,你可以連接到數據庫這樣的模塊:

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

確保您已經將腳本的頂部導入模塊import MySQLdb。在此之後,您可以開始使用數據庫。看到一個非常好的教程here

也看看here以及。