插入到mysql数据库中,pymysql无法插入

时间:2018-05-04 12:35:32

标签: python mysql pymysql

我试图将虚拟数据插入到mysql数据库中。

数据库结构如下:

database name: messaround database table name: test

表格结构:

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

下面的

更新2 方法和错误。 我有一种尝试插入via的方法:

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")

你能帮忙吗?

谢谢。

4 个答案:

答案 0 :(得分:2)

如果您使用代码:

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')

答案 1 :(得分:0)

通常在Python中,您将参数化查询传递给数据库驱动程序。见this example in PyMySQL's documentation;它使用占位符字符构造<?php /* * This file is part of jwt-auth. * * (c) Sean Tymon <tymon148@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ return [ /* |-------------------------------------------------------------------------- | JWT Authentication Secret |-------------------------------------------------------------------------- | | Don't forget to set this in your .env file, as it will be used to sign | your tokens. A helper command is provided for this: | `php artisan jwt:secret` | | Note: This will be used for Symmetric algorithms only (HMAC), | since RSA and ECDSA use a private/public key combo (See below). | */ // 'secret' => 'my-dummy-jwt-token', 'secret' => 'key', /* |-------------------------------------------------------------------------- | JWT Authentication Keys |-------------------------------------------------------------------------- | | The algorithm you are using, will determine whether your tokens are | signed with a random string (defined in `JWT_SECRET`) or using the | following public & private keys. | | Symmetric Algorithms: | HS256, HS384 & HS512 will use `JWT_SECRET`. | | Asymmetric Algorithms: | RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below. | */ 'keys' => [ /* |-------------------------------------------------------------------------- | Public Key |-------------------------------------------------------------------------- | | A path or resource to your public key. | | E.g. 'file://path/to/public/key' | */ 'public' => env('JWT_PUBLIC_KEY'), /* |-------------------------------------------------------------------------- | Private Key |-------------------------------------------------------------------------- | | A path or resource to your private key. | | E.g. 'file://path/to/private/key' | */ 'private' => env('JWT_PRIVATE_KEY'), /* |-------------------------------------------------------------------------- | Passphrase |-------------------------------------------------------------------------- | | The passphrase for your private key. Can be null if none set. | */ 'passphrase' => env('JWT_PASSPHRASE'), ], /* |-------------------------------------------------------------------------- | JWT time to live |-------------------------------------------------------------------------- | | Specify the length of time (in minutes) that the token will be valid for. | Defaults to 1 hour. | | You can also set this to null, to yield a never expiring token. | Some people may want this behaviour for e.g. a mobile app. | This is not particularly recommended, so make sure you have appropriate | systems in place to revoke the token if necessary. | */ //'ttl' => env('JWT_TTL', 60), 'ttl' => null, /* |-------------------------------------------------------------------------- | Refresh time to live |-------------------------------------------------------------------------- | | Specify the length of time (in minutes) that the token can be refreshed | within. I.E. The user can refresh their token within a 2 week window of | the original token being created until they must re-authenticate. | Defaults to 2 weeks. | | You can also set this to null, to yield an infinite refresh time. | Some may want this instead of never expiring tokens for e.g. a mobile app. | This is not particularly recommended, so make sure you have appropriate | systems in place to revoke the token if necessary. | */ 'refresh_ttl' => env('JWT_REFRESH_TTL', 20160), /* |-------------------------------------------------------------------------- | JWT hashing algorithm |-------------------------------------------------------------------------- | | Specify the hashing algorithm that will be used to sign the token. | | See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL | for possible values. | */ 'algo' => env('JWT_ALGO', 'HS256'), /* |-------------------------------------------------------------------------- | Required Claims |-------------------------------------------------------------------------- | | Specify the required claims that must exist in any token. | A TokenInvalidException will be thrown if any of these claims are not | present in the payload. | */ 'required_claims' => [ 'iss', 'iat', 'nbf', 'sub', 'jti', ], //'exp', remove token expire time /* |-------------------------------------------------------------------------- | Persistent Claims |-------------------------------------------------------------------------- | | Specify the claim keys to be persisted when refreshing a token. | `sub` and `iat` will automatically be persisted, in | addition to the these claims. | | Note: If a claim does not exist then it will be ignored. | */ 'persistent_claims' => [ // 'foo', // 'bar', ], /* |-------------------------------------------------------------------------- | Blacklist Enabled |-------------------------------------------------------------------------- | | In order to invalidate tokens, you must have the blacklist enabled. | If you do not want or need this functionality, then set this to false. | */ 'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true), /* | ------------------------------------------------------------------------- | Blacklist Grace Period | ------------------------------------------------------------------------- | | When multiple concurrent requests are made with the same JWT, | it is possible that some of them fail, due to token regeneration | on every request. | | Set grace period in seconds to prevent parallel request failure. | */ 'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0), /* |-------------------------------------------------------------------------- | Providers |-------------------------------------------------------------------------- | | Specify the various providers used throughout the package. | */ 'providers' => [ /* |-------------------------------------------------------------------------- | JWT Provider |-------------------------------------------------------------------------- | | Specify the provider that is used to create and decode the tokens. | */ 'jwt' => Tymon\JWTAuth\Providers\JWT\Namshi::class, /* |-------------------------------------------------------------------------- | Authentication Provider |-------------------------------------------------------------------------- | | Specify the provider that is used to authenticate users. | */ 'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class, /* |-------------------------------------------------------------------------- | Storage Provider |-------------------------------------------------------------------------- | | Specify the provider that is used to store tokens in the blacklist. | */ 'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class, ], ]; 查询,然后调用传递查询的INSERT和实际值的元组。

使用参数化查询也是recommended for security purposes,因为它会破坏许多常见的SQL注入攻击。

答案 2 :(得分:0)

你应该打印你生成的sql语句,这样可以更容易地看出错误。

但我猜您需要为'的字符串值引用",".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。

答案 3 :(得分:0)

更改您的查询,如下所示

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'])