简体   繁体   中英

how to store a huge string (length 50000) in mysql using python

how to store a huge string (length 50000) in mysql using python. I have a big string of length nearly 50000 .I have to store it into mysql. Some suggested to store the string as a blob or text type.

Can anyone help me how to convert string into blob type

def main():
    stringKey=''
    stringValues=''
    keys=ccv.keys()        //ccv is a dictionary data structure  
    vectors=ccv.values()  //ccv is a dictionary data structure 
    for key in keys:
            stringKey='#'.join(key for key in keys)
    for value in vectors:
            stringValues='$'.join(str(value) for value in vectors)
    insert(stringKey,stringValues)
    print 'insert successful'

def insert(k,v):
    db = mysql.connector.connect(user='root', password='abhi',
                              host='localhost',
                              database='cbir')

    sql= 'INSERT INTO ccv(key,vector) VALUES(%s,%s)'
    args = (k,v)
    cursor=db.cursor()
    cursor.execute(sql,args)
    db.commit()
    db.close()

error:

ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key,vector) VALUES('27:1:8#27:1:9#25:2:11#6:9:8#6:9:9#6:9:6#6:9:7#6:9:4#6:9:5#27' at line 1

You made a small error in:

'INSERT INTO ccv(key,vector) VALUES(%s,%s)'

It should be:

"INSERT INTO ccv (`key`, `vector`) VALUES(%s, %s)"

Notice the ` denoting the column names.

As Larry reminded me the values don't have to be quoted for parameterized queries.

If the fields are already set for longtext this should work without needing to convert the data to blobs.

The problem was only related to the syntax and not the data or column types.

您不需要转换字符串,您需要将数据库中的字段类型从 varchar 更改为 longtext。

You are not associating the arguments with the SQL statement.

You want

 cursor.execute(sql, args)

instead of

 cursor.execute(sql)
sql = "INSERT INTO ccv(`key`,`vector`) VALUES(%s,%s)"

这工作正常

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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