How do I connect to a MySQL Database in Python?

后端 未结 25 1552
眼角桃花
眼角桃花 2020-11-21 07:43

How do I connect to a MySQL database using a python program?

相关标签:
25条回答
  • 2020-11-21 08:22

    First install the driver (Ubuntu)

    • sudo apt-get install python-pip

    • sudo pip install -U pip

    • sudo apt-get install python-dev libmysqlclient-dev

    • sudo apt-get install MySQL-python

    MySQL database connection codes

    import MySQLdb
    conn = MySQLdb.connect (host = "localhost",user = "root",passwd = "pass",db = "dbname")
    cursor = conn.cursor ()
    cursor.execute ("SELECT VERSION()")
    row = cursor.fetchone ()
    print "server version:", row[0]
    cursor.close ()
    conn.close ()
    
    0 讨论(0)
  • 2020-11-21 08:23

    If you do not need MySQLdb, but would accept any library, I would very, very much recommend MySQL Connector/Python from MySQL: http://dev.mysql.com/downloads/connector/python/.

    It is one package (around 110k), pure Python, so it is system independent, and dead simple to install. You just download, double-click, confirm license agreement and go. There is no need for Xcode, MacPorts, compiling, restarting …

    Then you connect like:

    import mysql.connector    
    cnx = mysql.connector.connect(user='scott', password='tiger',
                                  host='127.0.0.1',
                                  database='employees')
    
    try:
       cursor = cnx.cursor()
       cursor.execute("""
          select 3 from your_table
       """)
       result = cursor.fetchall()
       print result
    finally:
        cnx.close()
    
    0 讨论(0)
  • 2020-11-21 08:24

    This is Mysql DB connection

    from flask import Flask, render_template, request
    from flask_mysqldb import MySQL
    
    app = Flask(__name__)
    
    
    app.config['MYSQL_HOST'] = 'localhost'
    app.config['MYSQL_USER'] = 'root'
    app.config['MYSQL_PASSWORD'] = 'root'
    app.config['MYSQL_DB'] = 'MyDB'
    
    mysql = MySQL(app)
    
    
    @app.route('/', methods=['GET', 'POST']) 
    def index():
        if request.method == "POST":
            details = request.form
            cur = mysql.connection.cursor()
            cur.execute ("_Your query_")
            mysql.connection.commit()
            cur.close()
            return 'success'
        return render_template('index.html')
    
    
    if __name__ == '__main__':
        app.run()
    
    0 讨论(0)
  • 2020-11-21 08:24

    First step to get The Library: Open terminal and execute pip install mysql-python-connector. After the installation go the second step.

    Second Step to import the library: Open your python file and write the following code: import mysql.connector

    Third step to connect to the server: Write the following code:

    conn = mysql.connector.connect(host=you host name like localhost or 127.0.0.1, username=your username like root, password = your password)

    Third step Making the cursor: Making a cursor makes it easy for us to run queries. To make the cursor use the following code: cursor = conn.cursor()

    Executing queries: For executing queries you can do the following: cursor.execute(query)

    If the query changes any thing in the table you need to add the following code after the execution of the query: conn.commit()

    Getting values from a query: If you want to get values from a query then you can do the following: cursor.excecute('SELECT * FROM table_name') for i in cursor: print(i) #Or for i in cursor.fetchall(): print(i)

    The fetchall() method returns a list with many tuples that contain the values that you requested ,row after row .

    Closing the connection: To close the connection you should use the following code: conn.close()

    Handling exception: To Handel exception you can do it Vai the following method: try: #Logic pass except mysql.connector.errors.Error: #Logic pass To use a database: For example you are a account creating system where you are storing the data in a database named blabla, you can just add a database parameter to the connect() method ,like

    mysql.connector.connect(database = database name)

    don't remove other informations like host,username,password.

    0 讨论(0)
  • 2020-11-21 08:25

    Oracle (MySQL) now supports a pure Python connector. That means no binaries to install: it's just a Python library. It's called "Connector/Python".

    http://dev.mysql.com/downloads/connector/python/

    0 讨论(0)
  • 2020-11-21 08:26

    for Python3.6 I found two driver: pymysql and mysqlclient. I tested the performance between them and got the result: the mysqlclient is faster.

    below is my test process(need install python lib profilehooks to analyze time elapse:

    raw sql: select * from FOO;

    immediatly execute in mysql terminal: 46410 rows in set (0.10 sec)

    pymysql (2.4s):

    from profilehooks import profile
    import pymysql.cursors
    import pymysql
    connection = pymysql.connect(host='localhost', user='root', db='foo')
    c = connection.cursor()
    
    @profile(immediate=True)
    def read_by_pymysql():
        c.execute("select * from FOO;")
        res = c.fetchall()
    
    read_by_pymysql()
    

    here's the pymysql profile:


    mysqlclient (0.4s)

    from profilehooks import profile
    import MySQLdb
    
    connection = MySQLdb.connect(host='localhost', user='root', db='foo')
    c = connection.cursor()
    
    @profile(immediate=True)
    def read_by_mysqlclient():
        c.execute("select * from FOO;")
        res = c.fetchall()
    
    read_by_mysqlclient()
    

    here's the mysqlclient profile:

    So, it seems that mysqlclient is much faster than pymysql

    0 讨论(0)
提交回复
热议问题