0

I have script that parse data from txt file(I think its utf8) and then it should write it to mysql. When I do something like that:

cur.execute("insert into keywords (keyword) values ('%s')" % (u'RUSSIAN TEXT HERE'))

it do the job well(I have russian string in my mysqldb), but when I

f = open('/Users/aaaa/Desktop/keywords.txt', 'rw+')
for x in range (14028):
 a = f.readline(x)
 cur.execute("insert into keywords (keyword) values ('%s')" % (a))
 #or that
 cur.execute("insert into keywords (keyword) values ('%s')" % (unicode(a)))

then I get this

'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

I have this in my mysql

character_set_client utf8
character_set_connection utf8
character_set_database utf8
character_set_filesystem binary
character_set_results utf8
character_set_server latin1
character_set_system utf8
character_sets_dir /usr/local/mysql-5.6.20-osx10.8-x86_64/share/charsets/

Occasionally, I wrote simbols into database, but russian symbols was like squares and stuff.
What should I do?

Also, I get this after repr(a)

''
'0'
'5 '
'ru '
'\xd0\xbc\xd0\xb0'
'\xd1\x85\xd0\xb0\xd1'
Traceback (most recent call last):
asked Oct 30, 2014 at 18:24
3
  • 1
    NEVER use the % operator to parametrize SQL queries. While using %s is correct, you have to pass the actual data tuple as another argument to cur.execute() - otherwise you perform string interpolation which leaves you open to sql injection. Commented Oct 30, 2014 at 18:35
  • ok thanks. But what should I do, to write data into mysql? Commented Oct 30, 2014 at 18:37
  • print repr(a) and post what it is when you crash Commented Oct 30, 2014 at 18:45

1 Answer 1

1

Try to open file this way:

f = open('/Users/aaaa/Desktop/keywords.txt', 'rw+', encoding='utf-8')

answered Oct 30, 2014 at 18:50
Sign up to request clarification or add additional context in comments.

1 Comment

f = codecs.open('/Users/alexeypolusov/Desktop/keywords.txt', encoding='utf-8', mode='rw+') here it is! THANKS DUDE

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.