[英]Connect mysql database in python
我创建了一个数据库,如下所示:
+------------+-------+--------------+-------------------------------+
| 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相同的表,并用相同的数据填充了该表。
很高兴将世界视为一组对象,因此我的解决方案将在一个类中完成,在该类中,我们需要将connexion参数保存到consutructor def __init__(self):
类的Python字典中的MySQL服务器中def __init__(self):
self.config = { 'user':'begueradj',
'passwd':'begueradj',
'host':'127.0.0.1',
'db':'begueradj',
}
当然,需要将这些参数更改为其参数。
当然,尝试自己做一个黑客不一定是最好的主意。 对于我的解决方案,我选择使用texttable
,可以通过以下方式安装:
sudo python setup.py install
执行完MySQL查询( self.sqlquery = """SELECT * FROM begueradj"""
)之后,您将需要MySQLCursor.description属性以元组格式获取列名:
# Get columns' names
self.columns = [i[0] for i in self.cursor.description]
请注意,当texttable
模块在列表上工作时,将元组转换为列表很有用。
我在下面评论了我的程序解决方案的几乎每一行:
'''
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.