简体   繁体   English

在python中连接mysql数据库

[英]Connect mysql database in python

I have created a DB as follows: 我创建了一个数据库,如下所示:

+------------+-------+--------------+-------------------------------+
| Reg_exp    | Token | Integer_code | Attribute_value               |
+------------+-------+--------------+-------------------------------+
| WHITESPACE | -     |            0 | -                             |
| begin      | begin |            1 | -                             |
| end        | end   |            2 | -                             |
| if         | if    |            3 | -                             |

I could access the tuples of the database using the following command: (I have not included the connection part but only the query) 我可以使用以下命令访问数据库的元组:(我没有包括连接部分,只有查询)

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!!!"

The result I get is: 我得到的结果是:

MATCH FOUND!!!
('begin', 'begin', 1L, '-')

I want to display the values in the form of a table along with the column names. 我想以表格的形式显示值以及列名。 How can I do that? 我怎样才能做到这一点?

May be my answer is not useful for the OP who has not been online since he asked this question, but may be it will be useful for future members facing the same problem. 自从他问这个问题以来一直未在线的OP可能对我的回答没有用,但对面临相同问题的未来成员也可能有用。

The OP is looking for a Python output in MySQL format: 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    |       |
+-----------------+-------------+------+-----+---------+-------+

(my DB and table have the same name, by the way) (顺便说一下,我的数据库和表具有相同的名称)

I created the same table as the OP's one and filled it with the same data. 我创建了与OP相同的表,并用相同的数据填充了该表。

It is good to see the world as a set of object, so my solution will be done in a class where we need to save the connexion parameters to MySQL server within a Python dictionary in the class consutructor def __init__(self): 很高兴将世界视为一组对象,因此我的解决方案将在一个类中完成,在该类中,我们需要将connexion参数保存到consutructor def __init__(self):类的Python字典中的MySQL服务器中def __init__(self):

self.config = { 'user':'begueradj',
                'passwd':'begueradj',
                'host':'127.0.0.1',
                'db':'begueradj',
               }

Of course, one needs to change these parameters to his ones. 当然,需要将这些参数更改为其参数。

Of course, trying to do a hack by yourself is not necessarily the best idea. 当然,尝试自己做一个黑客不一定是最好的主意。 For my solution, I opted for the use of texttable which you can install by: 对于我的解决方案,我选择使用texttable ,可以通过以下方式安装:

  • First download the compressed module. 首先下载压缩模块。
  • Uncompress the file and change the directory to it. 解压缩文件并更改目录。
  • Finally, type this command: sudo python setup.py install 最后,键入以下命令: sudo python setup.py install

After executing the MySQL query ( self.sqlquery = """SELECT * FROM begueradj""" ), you will need the MySQLCursor.description Property to get the columns' names in a tuple format: 执行完MySQL查询( self.sqlquery = """SELECT * FROM begueradj""" )之后,您将需要MySQLCursor.description属性以元组格式获取列名:

# Get columns' names
self.columns = [i[0] for i in self.cursor.description]

Note that is useful to transform the tuples to lists as texttable module works on lists. 请注意,当texttable模块在列表上工作时,将元组转换为列表很有用。

Python program: Python程序:

I commented almost each line of my program solution below: 我在下面评论了我的程序解决方案的几乎每一行:

'''
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()

Demo: 演示:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM