简体   繁体   English

将 Python 字符串或字典插入 MySQL

[英]Insert Python string or dictionary into MySQL

I have a Python string (or potentially a Python dictionary) that I'd like to insert to MySql table.我有一个 Python 字符串(或者可能是一个 Python 字典),我想插入到 MySql 表中。
My String is the following:我的字符串如下:

{'ticker': 'BTC', 'avail_supply': 16479075.0, 'prices': 2750.99, 'name': 'Bitcoin', '24hvol': 678995000.0}

这是我得到的错误

I have the same kind of error if I want to insert the Dict format.如果我想插入 Dict 格式,我有同样的错误。
I really don't understand this kind of error (ie the '\' in-between the components of the string).我真的不明白这种错误(即字符串组件之间的'\')。 How can I deal with this error?我该如何处理这个错误? Any why to properly insert a whole string to a particular TEXT cell in SQL?为什么要将整个字符串正确插入 SQL 中的特定 TEXT 单元格?
Many thanks !!非常感谢 !!

Here is how to connect, make a table, and insert in the table.下面介绍如何连接、制作表格和插入表格。

import MySQLdb as mdb
import sys
#connect
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');

with con:
    #need the cursor object so you can pass sql commands, also there is a dictionary cursor
    cur = con.cursor()
    #create example table
    cur.execute("CREATE TABLE IF NOT EXISTS \
        Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
    #insert what you want
    cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
    cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")

Example above will make a table with 2 cols, one ID and one name上面的示例将创建一个包含 2 列、一个 ID 和一个名称的表格

look here on an example on how to insert stuff from dictionary with keys and list as value to sql, basically you need place holders 在此处查看有关如何使用键从字典中插入内容并将其作为值列为 sql 的示例,基本上您需要占位符

sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}

conn = MySQLdb.connect(**params)

cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()

conn.close()

or you can go with this as an example for a simple straight forward dict或者你可以 go 以此作为简单直接的字典的例子

placeholders = ', '.join(['%s'] * len(myDict))
columns = ', '.join(myDict.keys())
sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cursor.execute(sql, myDict.values())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM