How do I connect to a MySQL Database in Python?

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

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

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

    Run this command in your terminal to install mysql connector:

    pip install mysql-connector-python
    

    And run this in your python editor to connect to MySQL:

    import mysql.connector
    
    mydb = mysql.connector.connect(
          host="localhost",
          user="yusername",
          passwd="password",
          database="database_name"
    )
    

    Samples to execute MySQL Commands (in your python edior):

    mycursor = mydb.cursor()
    mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
    mycursor.execute("SHOW TABLES")
    
    mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
    mydb.commit() # Use this command after insert or update
    

    For more commands: https://www.w3schools.com/python/python_mysql_getstarted.asp

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

    MySQLdb is the straightforward way. You get to execute SQL queries over a connection. Period.

    My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead. Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.

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

    Even though some of you may mark this as a duplicate and get upset that I am copying someone else's answer, I would REALLY like to highlight an aspect of Mr. Napik's response. Because I missed this, I caused nationwide website downtime (9min). If only someone shared this information, I could have prevented it!

    Here is his code:

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

    The important thing here is the Try and Finally clause. This allows connections to ALWAYS be closed, regardless of what happens in the cursor/sqlstatement portion of the code. A lot of active connections cause DBLoadNoCPU to spike and could crash a db server.

    I hope this warning helps to save servers and ultimately jobs! :D

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

    SqlAlchemy


    SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

    Installation

    pip install sqlalchemy
    

    RAW query

    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker, scoped_session
    
    engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
    session_obj = sessionmaker(bind=engine)
    session = scoped_session(session_obj)
    
    # insert into database
    session.execute("insert into person values(2, 'random_name')")
    session.flush()
    session.commit()
    

    ORM way

    from sqlalchemy import Column, Integer, String
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker, scoped_session
    
    Base = declarative_base()
    engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
    session_obj = sessionmaker(bind=engine)
    session = scoped_session(session_obj)
    
    # Bind the engine to the metadata of the Base class so that the
    # declaratives can be accessed through a DBSession instance
    Base.metadata.bind = engine
    
    class Person(Base):
        __tablename__ = 'person'
        # Here we define columns for the table person
        # Notice that each column is also a normal Python instance attribute.
        id = Column(Integer, primary_key=True)
        name = Column(String(250), nullable=False)
    
    # insert into database
    person_obj = Person(id=12, name="name")
    session.add(person_obj)
    session.flush()
    session.commit()
    
    0 讨论(0)
  • 2020-11-21 08:21

    PyMySQL 0.10.1 - Released: Sep 10, 2020, has support for python3 as well.

    python3 -m pip install PyMySQL
    

    Simple code:

    import pymysql
    
    # Connect to the database
    conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')
    
    # Create a Cursor object
    cur = conn.cursor()
    
    # Execute the query
    cur.execute("SELECT * FROM fax.student")
    
    # Read and print records
    for row in cur.fetchall():
        print(row)
    

    output:

    (1, 'Petar', 'Petrovic', 1813, 'Njegusi')
    (2, 'Donald', 'Tramp', 1946, 'New York')
    (3, 'Bill', 'Gates', 1955, 'Seattle')
    
    0 讨论(0)
  • 2020-11-21 08:22

    Also take a look at Storm. It is a simple SQL mapping tool which allows you to easily edit and create SQL entries without writing the queries.

    Here is a simple example:

    from storm.locals import *
    
    # User will be the mapped object; you have to create the table before mapping it
    class User(object):
            __storm_table__ = "user" # table name
            ID = Int(primary=True) #field ID
            name= Unicode() # field name
    
    database = create_database("mysql://root:password@localhost:3306/databaseName")
    store = Store(database)
    
    user = User()
    user.name = u"Mark"
    
    print str(user.ID) # None
    
    store.add(user)  
    store.flush() # ID is AUTO_INCREMENT
    
    print str(user.ID) # 1 (ID)
    
    store.commit() # commit all changes to the database
    

    To find and object use:

    michael = store.find(User, User.name == u"Michael").one()
    print str(user.ID) # 10
    

    Find with primary key:

    print store.get(User, 1).name #Mark
    

    For further information see the tutorial.

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