我不能让Python与mySQL一起工作

时间:2018-01-16 05:34:34

标签: python mysql connection pycharm database-connection

好的,所以我先写道,'我是Python新手'。我正在使用PyCharm来运行我正在构建的程序转储到数据库(本地托管的mySQL)。

不幸的是,我遇到了使用Python将数据导入数据库的问题,但是我能够通过phpMyAdmin web gui在SQL中插入数据。我一定错过了一些明显的东西。我正在为PyCharm使用'mysql.connector'插件。这是相关的代码。

那么,一开始我导入模块?像这样;

import mysql.connector     

此代码在一对while循环中被引用;

cnx = mysql.connector.connect(host ='localhost', user = 'root', passwd= '', db='weather_test01')
            c = cnx.cursor()
            c.execute("INSERT INTO 'stations' ('dtime', 'tmp', 'apptmp', 'dewpoint', 'relhum', 'delta_t', 'wind_dir', 'wind_spd_kmh', 'wind_gust_kmh', 'wind_spd_kts', 'wind_gust_kts', 'press_qnh', 'press_msl', 'rainsince9am') VALUES (dtime1, tmp1, apptmp1, dewpoint1, relhum1, delta_t1, wind_dir1, wind_spd_kmh1, wind_gust_kmh1, wind_spd_kts1, wind_gust_kts1, press_qnh1, press_msl1, rainsince9am1)")
            cnx.commit()      

请不要因为我写的方式而活着吃我,我是新的:) 其他重要因素;

  • 我能够让它输入数据几次(但是它作为NULL值传递给SQL。我的猜测是我传递了错误的数字格式?或者与db Collat​​ion有关?)< / LI>
  • 我也尝试过使用PyCharm的许多不同插件(所有这些插件似乎都以类似的方式实现)。
  • 我在插入的变量名称上使用和不使用引号来尝试它,我已经尝试了很多,我在我的智慧结束。

至于错误代码,这就是它目前的样子;

    C:\Users\logge\PycharmProjects\untitled3\venv\Scripts\python.exe C:/Users/logge/PycharmProjects/untitled3/main.py
Traceback (most recent call last):
  File "C:/Users/logge/PycharmProjects/untitled3/main.py", line 111, in <module>
    weather(1)
  File "C:/Users/logge/PycharmProjects/untitled3/main.py", line 101, in weather
    c.execute("INSERT INTO 'stations' ('dtime', 'tmp', 'apptmp', 'dewpoint', 'relhum', 'delta_t', 'wind_dir', 'wind_spd_kmh', 'wind_gust_kmh', 'wind_spd_kts', 'wind_gust_kts', 'press_qnh', 'press_msl', 'rainsince9am') VALUES (dtime1, tmp1, apptmp1, dewpoint1, relhum1, delta_t1, wind_dir1, wind_spd_kmh1, wind_gust_kmh1, wind_spd_kts1, wind_gust_kts1, press_qnh1, press_msl1, rainsince9am1)")
  File "C:\Users\logge\PycharmProjects\untitled3\venv\lib\site-packages\mysql\connector\cursor.py", line 561, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "C:\Users\logge\PycharmProjects\untitled3\venv\lib\site-packages\mysql\connector\connection.py", line 525, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "C:\Users\logge\PycharmProjects\untitled3\venv\lib\site-packages\mysql\connector\connection.py", line 427, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''stations' ('dtime', 'tmp', 'apptmp', 'dewpoint', 'relhum', 'delta_t', 'wind_dir' at line 1

Process finished with exit code 1     

错误代码中提到的“第101行”是在我发布的第二部分代码中讨论以“c.execute ... INSERT”开头的行。

以下是我也尝试过的代码,只是为了看看我是否能得到任何结果(虽然我仍然得到相同的错误):

from __future__ import print_function
from datetime import date, datetime, timedelta
import mysql.connector

dtime1 = 1
tmp1 = 5
apptmp1 = 2
dewpoint1 = 64
relhum1 = 3
delta_t1 = 4
wind_dir1 = 5
wind_spd_kmh1 = 6
wind_gust_kmh1 = 7
wind_spd_kts1 = 8
wind_gust_kts1 = 9
press_qnh1 = 10
press_msl1 = 11
rainsince9am1 =12


cnx = mysql.connector.connect(host ='localhost', user = 'root', passwd= '', db='weather_test01')
cursor = cnx.cursor()

tomorrow = datetime.now().date() + timedelta(days=1)

add_employee = ("INSERT INTO stations "
               "(dtime, tmp, apptmp, dewpoint, relhum, delta_t, wind_dir, wind_spd_kmh, wind_gust_kmh, wind_spd_kts, wind_gust_kts, press_qnh, press_msl, rainsince9am) "
               "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,)")

data_employee = (dtime1, tmp1, apptmp1, dewpoint1, relhum1, delta_t1, wind_dir1, wind_spd_kmh1, wind_gust_kmh1, wind_spd_kts1, wind_gust_kts1, press_qnh1, press_msl1, rainsince9am1)

# Insert new employee
cursor.execute(add_employee, data_employee)
emp_no = cursor.lastrowid



# Make sure data is committed to the database
cnx.commit()

cursor.close()
cnx.close()         

非常感谢任何帮助或建议。如果需要,我很乐意发布整个代码。我只是不想把这整件事弄得一团糟。

2 个答案:

答案 0 :(得分:0)

Bellow代码可以将SQL数据转换为NoSQL数据。对于SQL我使用MySQL服务器和NoSQL我使用MongoDB。 这是代码

    from os import getenv
    import pymssql
    import json 
    from pymongo import MongoClient

    server = "192.168.1.1"
    user = "root"
    password = "root"


    #MS SQL SERVER CONNECT 
    conn = pymssql.connect(server, user, password, "database_name")
    cursor = conn.cursor()

    #MONGODB CONNECT
    #27017 is default port for mongodb 
    conn = MongoClient('localhost',27017,username="user_name", password="password")
    db = conn['in']
    col = db['nclt_details']
    cursor.execute('SELECT * FROM collection_name')

    for row in cursor:
        data_h = dict()
        data_h['id'] =  row[0]
        data_h['case_no'] =  row[1]
        data_h['tp_no'] =  row[2]
        data_h['section'] =  row[3]
        data_h['purpose'] =  row[4]
        data_h['petitioner'] =  row[5]
        data_h['petitioner_others'] =  row[6]
        data_h['respondent'] =  row[7]
        data_h['respondent_others'] =  row[8]
        data_h['petitioner_advocate'] =  row[9]
        data_h['respondent_advocate'] =  row[10]
        data_h['Remarks'] = row[11]
        col.insert(data_h)
    conn.close()

答案 1 :(得分:0)

我发现了你的错误。您已将输入数据引用为字符串(%s)。但是你输入的是整数(数字)。

如果您想将数字作为字符串放在第一个代码块(您的代码)中,则需要输入str(variable)而不是variable。在第二块代码中(从MySQL复制),您可以使用引号将变量声明为variable = "0000"

如果您希望在代码中使用数字,请将表格结构更改为INTEGERDOUBLE,而不是VARCHARCHAR

我认为该表存在并且所有字段都存在,因为没有错误连接到数据库并找到该表。