sql - Python SQLite3 - Table Output Format Question & Handling IntegrityError -
i have table created using python + sqlite3
c.execute('create table if not exists reg(col1 text primary key, col2 text)')
i wrote record using val1 , val2 variables have string values (urls specific)
c.execute('insert reg values(?,?)', (val1, val2))
now when print table using code
c.execute('select * reg') rows = c.fetchall() print rows
it shows output as
[(u'http://www.someurl.com', u'http://www.someurl.com/somedir/')]
now, u in front of column values mean?
edit: next doubt in continuation question updating thread instead of creating new one. have updated title too. hope that's ok.
from above code, clear col1 primary key. so, when tried purposefully insert same records second time throws exception
integrityerror: column col1 not unique
in order handle this, modified code this...
try: c.execute('insert reg values(?,?)', (val1, val2)) except sqlite3.integrityerror: print val1+ " in database"
now executing code caused me exception
traceback (most recent call last): file "c:\documents , settings\user\desktop\dburl.py", line 47, in <module> c.execute('insert reg values(?,?)', (val1,val2)) operationalerror: database locked
any idea how resolve this? infact, don't understand operationerror mean , made db locked?
the u
means unicode strings. can encoded character set want:
u'http://www.someurl.com'.encode('ascii') # or 'latin-1' or 'utf-8'
you'll same string without u
because they're ascii characters.
see http://docs.python.org/howto/unicode.html.
if strings contain ascii characters (all normal symbols on english keyboard) don't have worry this. if, however, you're using extended character set, need make sure you're specifying right encoding when saving strings or displaying them user.
edit: when execute
import sqlite3 con = sqlite3.connect(":memory:") con.isolation_level = none c = con.cursor() val1, val2 = 'a', 'b' c.execute('create table if not exists reg(col1 text primary key, col2 text)') c.execute('insert reg values(?,?)', (val1, val2)) try: c.execute('insert reg values(?,?)', (val1, val2)) except sqlite3.integrityerror: print val1, "is in database"
i a in database
. (note proper way print statement, although yours valid.) problem somewhere else -- locked
means else writing database. try in memory database did, know sure nothing else accessing it. if works, problem exception indicates -- else accessing database.
Comments
Post a Comment