【问题标题】:Executing mysql commands in python script在python脚本中执行mysql命令
【发布时间】:2016-04-06 02:57:08
【问题描述】:

是否可以在 python 脚本中执行以下 mysql 命令?

mysql> 显示数据库;

mysql> 显示表;

例如,在 python 脚本中执行 sql 查询可以通过以下方式完成:

connection = MySQLdb.connect()
cursor = connection.cursor()
cursor.execute("select * from table;")

如何写这个来执行mysql命令?

动机是使用“显示表​​”比编写 sql 语句来显示数据库中的所有表名更快。

【问题讨论】:

  • show database 不是 SQLite 命令。你的实际目标是什么?
  • 感谢您的收获!更新了问题。
  • "show tables" 更快,因为它只输出一条错误消息。

标签: python mysql sqlite


【解决方案1】:
import sqlite3 as lite
import sys

con = None


con = lite.connect('dbname')

cur = con.cursor()    
cur.execute('select * from table')

rows = cur.fetchall()

for row in rows:
   print row

【讨论】:

  • Try 块需要以下 except 块。您是否打算捕获任何特定的异常?
【解决方案2】:

SQLite 库被设计为嵌入式数据库,因此它不会执行对应用程序无用的命令。

.tables这个命令,不过是sqlite3 command-line shell实现的,不是SQLite自己实现的,所以不能通过Python实现。您必须使用内置机制,例如 PRAGMA database_listSELECT name FROM sqlite_master WHERE type = 'table';

【讨论】:

    最近更新 更多