我正在为Python创建一个Mysql Wrapper,主要是为了学习语言的来龙去脉等。尽管我偶然发现了一个找不到解决方案的问题。
运行脚本时,尽管我的数据库没有更新,但没有引发异常。我玩过DB游标,例如关闭它们,在函数中创建新游标等。但是结果仍然相同。
aka:cursor.rowcount -1
连接到数据库:
class magicDB:
myDB = None
DB_Cursor = None
def __init__(self,host, user, passwd, DB=None):
global myDB
self.host = host
self.user = user
self.DB = DB
if self.DB is None:
myDB = mysql.connector.connect(
host= host,
user= user,
passwd= passwd)
#DB_Cursor = myDB.cursor()
else:
myDB = mysql.connector.connect(
host= host,
user= user,
passwd= passwd,
database=DB)
#DB_Cursor = myDB.cursor()
def insert(self,table_name, params):
fields = ''
values = ''
placeholders = ''
query = '"INSERT INTO {} '. format(table_name)
for key in params:
fields = fields + str(key) + ', '
values = values + str(params[key]) + ', '
placeholders = placeholders + str('%s, ')
fields = fields[:-2]
values = values[:-2]
placeholders = placeholders[:-2]
query = query + '(' + fields + ')' + ' VALUES ' + '(' + placeholders + ')"'
print(query)
try:
Cursor = myDB.cursor()
Cursor.execute(operation=query, params=values, multi=True)
myDB.commit()
print(Cursor.rowcount, ' Record inserted')
except mysql.connector.Error as error:
print (error)
finally:
Cursor.close()
这是调用函数的主要模块:
from db_magic import magicDB
conn = magicDB(host='localhost', user='***', passwd='****', DB='testing')
print(conn)
# print(conn.DB_create('testing2'))
conn.insert(table_name= 'users', params={
'user_name': 'John Doe',
'email' : 'test@123.com',
'password': 'test'
} )
print(conn.Close_conn())
我试图理解我在这里做错了什么,因为没有抛出异常。
解决方案:
将值更改为列表而不是字符串。
def insert(self,table_name, params):
fields = ''
values = [] # changed to List instead of String
placeholders = ''
query = 'INSERT INTO {} '. format(table_name)
for key in params:
fields = fields + str(key) + ', '
values.append(params[key])
placeholders = placeholders + str('%s, ')
fields = fields[:-2]
placeholders = placeholders[:-2]
query = query + '(' + fields + ')' + ' VALUES ' + '(' + placeholders + ')'
print(query)
print(values)
try:
Cursor = myDB.cursor()
Cursor.execute(operation=query, params=values, multi=False)
myDB.commit()
print(Cursor.rowcount, ' Record inserted')
except mysql.connector.Error as error:
print(error)
except:
print ('Some errors')
finally:
Cursor.close()
答案 0 :(得分:0)
Values变量用作字符串,MYSQL-连接器不会迭代该字符串。为了解决这个问题,我将“值变量”更改为列表:
def insert(self,table_name, params):
fields = ''
values = [] # changed to List instead of String
placeholders = ''
query = 'INSERT INTO {} '. format(table_name)
for key in params:
fields = fields + str(key) + ', '
values.append(params[key])
placeholders = placeholders + str('%s, ')
fields = fields[:-2]
placeholders = placeholders[:-2]
query = query + '(' + fields + ')' + ' VALUES ' + '(' + placeholders + ')'
print(query)
print(values)
try:
Cursor = myDB.cursor()
Cursor.execute(operation=query, params=values, multi=False)
myDB.commit()
print(Cursor.rowcount, ' Record inserted')
except mysql.connector.Error as error:
print(error)
except:
print ('Some errors')
finally:
Cursor.close()