簡體   English   中英

pymysql無法插入到mysql數據庫中

[英]insert into mysql database with pymysql failing to insert

我正在嘗試將偽數據插入mysql數據庫。

數據庫結構如下:

database name: messaround database table name: test

表結構:

id (Primary key, auto increment) path (varchar(254))

下面的UPDATED 2方法和錯誤。 我有一種嘗試通過以下方式插入的方法:

def insert_into_db(dbcursor, table, *cols, **vals):
    try:
        query = "INSERT INTO {} ({}) VALUES ('{}')".format(table, ",".join(cols),  "'),('".join(vals))  
        print(query)
        dbcursor.execute(query)
        dbcursor.commit()
        print("inserted!")
    except pymysql.Error as exc:
        print("error inserting...\n {}".format(exc))

connection=conn_db()        
insertstmt=insert_into_db(connection, table='test', cols=['path'], vals=['test.com/test2'])

但是,這是失敗的說法:

INSERT INTO test () VALUES ('vals'),('cols')
error inserting...
 (1136, "Column count doesn't match value count at row 1")

你能幫忙嗎?

謝謝。

如果您使用代碼:

def insert_into_db(dbcursor, table, *cols, **vals):
    query = "INSERT INTO {} ({}) VALUES ({})".format(table,",".join(cols), ",".join(vals))
    print(query)

insert_into_db('cursor_here', 'table_here', 'name', 'city', name_person='diego', city_person='Sao Paulo')

Python返回:

INSERT INTO table_here (name,city) VALUES (name_person,city_person)

現在與其他:

def new_insert_into_db(dbcursor, table, *cols, **vals):
    vals2 = ''
    for first_part, second_part in vals.items():
        vals2 += '\'' + second_part + '\','
    vals2 = vals2[:-1]
    query = "INSERT INTO {} ({}) VALUES ({})".format(table,",".join(cols), vals2)
    print(query)

new_insert_into_db('cursor_here', 'table_here', 'name', 'city', name_person='diego', city_person='Sao Paulo')

Python將返回正確的SQL:

INSERT INTO table_here (name,city) VALUES ('diego','Sao Paulo')

通常,在Python中,您將參數化查詢傳遞給DB驅動程序。 請參閱PyMySQL文檔中的示例 它使用占位符構造一個INSERT查詢,然后調用傳遞查詢的cursor.execute()和實際值的元組。

為了安全起見 ,還建議使用參數化查詢,因為它可以克服許多常見的SQL注入攻擊。

您應該打印所生成的sql語句,這樣可以更輕松地發現問題所在。

但我想您需要在字符串",".join(vals)的字符串值",".join(vals)引號' (以防萬一有字符串值。
所以你的代碼正在產生

insert into test (path,) values (test.com/test2,);

但它應該產生

insert into test (`path`) values ('test.com/test2');

否則,請嘗試https://github.com/markuman/MariaSQL/ ,這使得使用pymysql將數據插入MariaDB / MySQL非常容易。

如下更改查詢

query = "INSERT INTO {} ({}) VALUES ('{}')".format(table, ",".join(cols),  "'),('".join(vals))

使用join時,該變量應該是列表,而不是字符串

table = 'test'
cols = ['path']
vals = ['test.com/test2', 'another.com/anothertest']


print(query)

"INSERT INTO test (path) VALUES ('test.com/test2'),('another.com/anothertest')"

更新:

def insert_into_db(dbconnection=None, table='', cols=None, vals=None):
    mycursor = dbconnection.cursor()
    if not (dbconnection and table and cols and vals):
        print('Must need all values')
        quit()
    try:
        query = "INSERT INTO {} ({}) VALUES ('{}')".format(table, ",".join(cols),  "'),('".join(vals))
        mycursor.execute(query)
        dbconnection.commit()
        print("inserted!")
    except pymysql.Error as exc:
        print("error inserting...\n {}".format(exc))


connection=conn_db()        

insertstmt=insert_into_db(dbconnection=connection, table='test', cols=['path'], vals=['test.com/test2'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM