How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  温柔的废话
    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')
    

提交回复
热议问题