首页 > 解决方案 > 如何将mysql局部变量传递给python?

问题描述

我想使用 MySQLdb 模块将局部变量从 MySQL 传递给 python。

我知道有很多关于其他方式的答案(从 python 到 mysql),我不是在寻找那个。

我也知道如何使用从表中获取任何数据

SELECT data_name 
FROM table_name

可以获取受影响的行以获取结果。

但是,SELECT @my_variable从 python 运行 a 返回一个空结果。

LOCK TABLES `usedID` WRITE;

 /...*Do some stuff here*/

SELECT `lastaugID` FROM `usedID` INTO @ID;
UNLOCK TABLES;
SELECT @ID;

从 mysql 执行上面的代码片段会返回预期的结果:

+-------+
| @ID   |
+-------+
| 58404 |
+-------+
1 row in set (0.00 sec)

但是传递给 python 的值是一个空列表。

这是进行 SQL 查询的 python 片段:

def write_sql(self, sqlreq, sqlreqdict):
  if self.sockname:
      con = MySQLdb.Connect( unix_socket=self.sockname, user=self.sqluser,
                             passwd=self.sqlpasswd, db=self.sqldb,
                             cursorclass=MySQLdb.cursors.DictCursor );
  else:
      con = MySQLdb.Connect( host=self.sqlhost, user=self.sqluser,
                             passwd=self.sqlpasswd, db=self.sqldb,
                             cursorclass=MySQLdb.cursors.DictCursor );
  cursor = con.cursor();
  try:
      cursor.execute( sqlreq, sqlreqdict );
  except MySQLdb.IntegrityError, val:
      html.print_errmsg_exit( "Database integrity error: " + str(val) );
  res = cursor.fetchall();

  del cursor;
  con.commit();
  con.close();
  # Re-open the read-only cursors of the DB, to be able to process
  # a request to read the just-created  file:
  self.init_db();

return res

PS:为什么不直接从表中读取?我需要锁定表并在解锁之前读取值。如果我在解锁后阅读,我可能会得到一个已被另一个会话更改的值。

标签: pythonmysqlmysql-python

解决方案


推荐阅读