How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  情深已故
    2020-11-21 08:03

    As a db driver, there is also oursql. Some of the reasons listed on that link, which say why oursql is better:

    • oursql has real parameterization, sending the SQL and data to MySQL completely separately.
    • oursql allows text or binary data to be streamed into the database and streamed out of the database, instead of requiring everything to be buffered in the client.
    • oursql can both insert rows lazily and fetch rows lazily.
    • oursql has unicode support on by default.
    • oursql supports python 2.4 through 2.7 without any deprecation warnings on 2.6+ (see PEP 218) and without completely failing on 2.7 (see PEP 328).
    • oursql runs natively on python 3.x.

    So how to connect to mysql with oursql?

    Very similar to mysqldb:

    import oursql
    
    db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
    cur=db_connection.cursor()
    cur.execute("SELECT * FROM `tbl_name`")
    for row in cur.fetchall():
        print row[0]
    

    The tutorial in the documentation is pretty decent.

    And of course for ORM SQLAlchemy is a good choice, as already mentioned in the other answers.

提交回复
热议问题