当我尝试将数据插入mysql时,也在db" db_of_lj"中创建一个表,发生了一些错误,但我不知道原因。 此外,我尝试打印(cursor.description)但输出是"无"。 我希望你能帮助我,谢谢!
import pymysql
def create_city_table(city):
#create table
global cursor
cursor.execute("drop table if exists %s" % (city))
create_table="create table %s(id int(10) not null primary key auto_increment," \
"total_price int(10)," \
"unitPrice int(10)," \
"room_desc varchar(20)," \
"construction_year int(10)," \
"area float," \
"location varchar(20));"
try:
cursor.execute(create_table % (city))
except :
print("Failed to create that table!")
return None
print("Successfully create table of '%s' in sql_db!" % city)
#connect to mysql
connect=pymysql.Connect(
host="127.0.0.1",
port=3306,
user="root",
password="1111",
db="db_of_lj"
)
#set a cursor
cursor = connect.cursor()
create_city_table("hangzhou")
insert2db = "insert into hangzhou(id,total_price,unitPrice,room_desc,construction_year,area,location)" \
" values(%d,%d,%d,%s,%d,%lf,%s)"
try:
print(cursor.description)
cursor.execute(insert2db % (1,2,3,"room_desc",2016,2.4,"xiasha"))
connect.commit()
except:
connect.rollback()
print("Failed to insert into database!")
exit(0)
print("Insert into the database successfully!")
没有try-catch,错误返回是:
Traceback (most recent call last):
File "D:/desktop/Computer/Python/web_scrapping/;project3_lianjia/exm.py", line 40, in <module>
cursor.execute(insert2db % (1,2,3,"room_desc",2016,2.4,"xiasha"))
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\cursors.py", line 165, in execute
result = self._query(query)
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\cursors.py", line 321, in _query
conn.query(q)
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\connections.py", line 860, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\connections.py", line 1061, in _read_query_result
result.read()
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\connections.py", line 1349, in read
first_packet = self.connection._read_packet()
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\connections.py", line 1018, in _read_packet
packet.check_error()
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\connections.py", line 384, in check_error
err.raise_mysql_exception(self._data)
File "C:\Users\94257\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.InternalError: (1054, "Unknown column 'xiasha' in 'field list'")