def marks_insert(name, pos_x, pos_y, start_offset, mark_points):
global conn
global cursor
sql = "insert into marks (name, pos_x, pos_y, start_offset, mark_points)\
values ({},{},{},{},{});".format(name,pos_x,pos_y,start_offset,mark_points)
cursor.execute(sql)
conn.commit()
看出name和mark_points是vchar类型的变量,在python里面name和mark_points用str转换为string类型,但是插入时出现以下错误:
name = 'door'时出现:
1054, "Unknown column 'name' in 'field list'"
mark_points = '[[404,57],[387,436],[613,426],[660,42],[414,50]]'时,出现以下错误:
(1064, "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 '[[404, 57], [387, 436], [613, 426], [660, 42], [414, 50]])' at line 1")
经过查阅了mysql如何存储python里的矩阵,也没查到,最后发现,使用的pymysql在插入数据的时候,如果是vchar类型的,需要加入单引号,即name = "'door'",其中还要有一个引号,对应矩阵存储,要先用str()进行转化,然后在加单引号才能成功。
python里面提供了repr()函数可以自动将其加上引号,所以,
def marks_insert(name, pos_x, pos_y, start_offset, mark_points):
global conn
global cursor
sql = "insert into marks (name, pos_x, pos_y, start_offset, mark_points)\
values ({},{},{},{},{});".format(repr(name),pos_x,pos_y,start_offset,repr(mark_points))
cursor.execute(sql)
conn.commit()