2

解決策が見つかりません。この質問について教えてください。

    dic={'username':u'\uc774\ud55c\ub098','userid':u'david007', 'nation':u'\ub300\ud55c\ubbfc\uad6d'}
    c=MySQLdb.connect(host=ddb['host'],user=ddb['user'],passwd=ddb['passwd'],db=ddb['db'], use_unicode=True, charset="utf8")
    s=c.cursor()
    sql="INSERT INTO "+db+" "+col+" VALUES "+str(tuple(dic.values()))
    s.execute(sql)

    "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 ''\\uc774\\ud55 ... at line 1")

    print sql
    INSERT INTO user_tb (username, userid, nation) VALUES (u'\uc774\ud55c\ub098', u'david007', u'\ub300\ud55c\ubbfc\uad6d')

エラーは次のとおりです。

4

1 に答える 1

4

パラメータ化されたクエリを使用する必要があります。

sql = "INSERT INTO " + db + " " + col + " VALUES (%s, %s, %s)"
s.execute(sql, dic.values())

タプルをクエリに単純に連結するuと、Unicode 文字列のプレフィックスによってそれらの文字列が無効な SQL になります。パラメーターを使用すると、MySQLdb はパラメーターの置換 (つまり、Unicode 文字列をバイト表現にエンコードする) で正しいことを行い、有効な SQL を生成します。

とにかく、一般的な原則として、クエリでは常にパラメーターを使用して SQL インジェクションを防ぐ必要があります。

于 2012-11-13T08:35:39.327 に答える