用python连接mysql数据库
我创建了一个DB,如下所示:用python连接mysql数据库,python,mysql,Python,Mysql,我创建了一个DB,如下所示: +------------+-------+--------------+-------------------------------+ | Reg_exp | Token | Integer_code | Attribute_value | +------------+-------+--------------+-------------------------------+ | WHITESPACE | - |
+------------+-------+--------------+-------------------------------+
| Reg_exp | Token | Integer_code | Attribute_value |
+------------+-------+--------------+-------------------------------+
| WHITESPACE | - | 0 | - |
| begin | begin | 1 | - |
| end | end | 2 | - |
| if | if | 3 | - |
我可以使用以下命令访问数据库的元组:我没有包括连接部分,只有查询
if input == str1:
print "MATCH FOUND!!!"
sql = "SELECT * FROM EXPRESSION WHERE Integer_code = 1"
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print (row[0], row[1], row[2], row[3])
except:
print "failed!!!"
我得到的结果是:
MATCH FOUND!!!
('begin', 'begin', 1L, '-')
我想以表格的形式显示这些值以及列名。我该怎么做呢?也许我的回答对OP没有用处,因为他问了这个问题,但可能对未来面临同样问题的成员有用 OP正在寻找MySQL格式的Python输出:
mysql> SHOW COLUMNS FROM begueradj FROM begueradj;
+-----------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+-------+
| Reg_exp | varchar(20) | NO | | NULL | |
| Token | varchar(20) | NO | | NULL | |
| Integer_code | int(2) | NO | | NULL | |
| Attribute_value | varchar(2) | NO | | NULL | |
+-----------------+-------------+------+-----+---------+-------+
顺便说一下,我的数据库和表有相同的名称
我创建了与OP相同的表,并用相同的数据填充它
将世界视为一组对象是很好的,因此我的解决方案将在一个类中完成,在该类中,我们需要将连接参数保存到类constructor def__init__self中的Python字典中的MySQL服务器:
当然,需要将这些参数更改为自己的参数
当然,尝试自己做一个黑客不一定是最好的主意。对于我的解决方案,我选择了使用,您可以通过以下方式安装:
首先下载压缩模块。
解压缩文件并将目录更改为该文件。
最后,键入以下命令:sudo python setup.py install
在执行MySQL query self.sqlquery=SELECT*FROM begueradj之后,您需要以元组格式获取列的名称:
# Get columns' names
self.columns = [i[0] for i in self.cursor.description]
注意,当texttable模块处理列表时,将元组转换为列表非常有用
Python程序:
我对我的程序解决方案的几乎每一行都发表了以下评论:
'''
Created on Mar 3, 2016
@author: begueradj
'''
import MySQLdb
import texttable
class Begueradj:
""" Display MySQL table's content along with
table's columns name as in pure MySQL format.
"""
def __init__(self):
""" Initialize MySQL server login parameters.
Try to connect to communicate with MySQL database.
"""
self.config = {'user':'begueradj',
'passwd':'begueradj',
'host':'127.0.0.1',
'db':'begueradj',
}
# Try to log to MySQL server
try:
self.dbconnexion = MySQLdb.connect(**self.config)
except MySQLdb.Error:
print "Database connexion failure!"
# Read the content of the MySQL table
self.sqlquery = """SELECT * FROM beg"""
def begueradj(self):
""" Display MySQL table data.
"""
self.cursor = self.dbconnexion.cursor()
self.cursor.execute(self.sqlquery)
# Get columns' names
self.columns = [i[0] for i in self.cursor.description]
self.tab = texttable.Texttable()
self.tablerow = [[]]
# Fetch all the rows from the query
self.data = self.cursor.fetchall()
# Must transform each tuple row to a list
for r in self.data:
self.tablerow.append(list(r))
# Get the number of columns of the table
self.tab.add_rows(self.tablerow)
# Align displayed data within cells to left
self.tab.set_cols_align(['l','l','l','l'])
# Once again, convert each tuple row to a list
self.tab.header(list(self.columns))
# Display the table (finally)
print self.tab.draw()
# Don't forget to close the connexion.
self.dbconnexion.close()
# Main program
if __name__=="__main__":
b=Begueradj()
b.begueradj()
演示:
对不起,刚才的事。我不知怎么误解了你的问题。我认为cursor.description将获得列名,可能还有作为元组的其他列元数据。嗯,看起来你也可以使用DictCursor。
'''
Created on Mar 3, 2016
@author: begueradj
'''
import MySQLdb
import texttable
class Begueradj:
""" Display MySQL table's content along with
table's columns name as in pure MySQL format.
"""
def __init__(self):
""" Initialize MySQL server login parameters.
Try to connect to communicate with MySQL database.
"""
self.config = {'user':'begueradj',
'passwd':'begueradj',
'host':'127.0.0.1',
'db':'begueradj',
}
# Try to log to MySQL server
try:
self.dbconnexion = MySQLdb.connect(**self.config)
except MySQLdb.Error:
print "Database connexion failure!"
# Read the content of the MySQL table
self.sqlquery = """SELECT * FROM beg"""
def begueradj(self):
""" Display MySQL table data.
"""
self.cursor = self.dbconnexion.cursor()
self.cursor.execute(self.sqlquery)
# Get columns' names
self.columns = [i[0] for i in self.cursor.description]
self.tab = texttable.Texttable()
self.tablerow = [[]]
# Fetch all the rows from the query
self.data = self.cursor.fetchall()
# Must transform each tuple row to a list
for r in self.data:
self.tablerow.append(list(r))
# Get the number of columns of the table
self.tab.add_rows(self.tablerow)
# Align displayed data within cells to left
self.tab.set_cols_align(['l','l','l','l'])
# Once again, convert each tuple row to a list
self.tab.header(list(self.columns))
# Display the table (finally)
print self.tab.draw()
# Don't forget to close the connexion.
self.dbconnexion.close()
# Main program
if __name__=="__main__":
b=Begueradj()
b.begueradj()