How do I connect to a MySQL Database in Python?

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

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

25条回答
  •  北恋
    北恋 (楼主)
    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.

提交回复
热议问题