回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<pre><code>import csv, sqlite3
conn = sqlite3.connect("mycustomers9.sql")
curs = conn.cursor()
try:
curs.execute("CREATE TABLE t (unknown1 TEXT, county TEXT, businessName TEXT, address1 TEXT, city1 TEXT, zip1 INTEGER, phone1 INTEGER,Email1 TEXT, approvalstatus TEXT, date1 TEXT, date2 TEXT, typeofConstruct TEXT, typeofBiz TEXT, unknown2 TEXT, unknown3 TEXT, unknown4 TEXT, unknown5 TEXT, unknown6 TEXT,BizName2 TEXT,Address2 TEXT, City2 TEXT,Zip2 TEXT,Country2 TEXT,Phone2 TEXT,Email2 TEXT,Phone3 TEXT);")
except sqlite3.OperationalError:
print "Table already exist"
with open('HR_plan_review.csv', 'rb') as infile:
dr = csv.DictReader(infile, delimiter = ',')
to_db = [(i["unknown1"], i['county'], i['businessName'], i['address1'], i['city1'], i['zip1'], i['phone1'], i['Email1'], i['approvalstatus'], i['date1'],i['date2'], i['typeofConstruct'], i['typeofBiz'], i['unknown2'], i['unknown3'], i['unknown4'], i['unknown5'], i['unknown6'], i['BizName2'], i['Address2'], i['City2'], i['Zip2'], i['Country2'], i['Phone2'], i['Email2'], i['Phone3']) for i in dr]
curs.executemany("INSERT INTO t (unknown1, county, businessName, address1, city1,zip1, phone1, Email1, approvalstatus, date1, date2,typeofConstruct, typeofBiz, unknown2, unknown3, unknown4,unknown5, unknown6,BizName2,Address2, City2,Zip2,Country2,Phone2,Email2,Phone3) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", to_db)
</code></pre>
<p>to_db返回一个以utf-8编码的列表,sqllite数据库似乎正在请求以unicode格式进行格式化。在运行上面的sql语句之前,如何将“to_db”列表转换为unicode。下面是我运行上述代码时得到的错误消息。在</p>
<blockquote>
<p>sqlite3.ProgrammingError: You must not use 8-bit bytestrings unless
you use a te xt_factory that can interpret 8-bit bytestrings (like
text_factory = str). It is highly recommended that you instead just
switch your application to Unicode str ings.</p>
</blockquote>
<h3>根据答案输入进行编辑</h3>
<p>修改后的代码(如下)现在成功执行,但它没有将从csv获取的值插入数据库。在</p>
^{pr2}$