To create a new MySQL connection, you need to import the MySQL Connector, then create the connection object, verify the connection, create the cursor object, execute the query, retrieve the results, and finally close the connection.
How to create a new MySQL connection
To create a new MySQL connection, you can use the following steps:
1. Import MySQL Connector
Import MySQL Connector so that your programming language can communicate with the MySQL database. For example, in Python you would use import mysql.connector
.
2. Create a connection object
Use the mysql.connector.connect()
function to create a connection object, which accepts the following parameters:
For example:
import mysql.connector my_connection = mysql.connector.connect( host="localhost", user="root", password="my_password", database="my_database", )
3. Verify the connection
Check whether the connection object is successfully established, you can use theis_connected()
function:
if my_connection.is_connected(): print("连接成功!") else: print("连接失败。")
4. Create a cursor object
Cursor objects allow you to execute SQL queries and retrieve results. Use the connection.cursor()
method to create a cursor object:
my_cursor = my_connection.cursor()
5. Execute the query
Use the execute() of the cursor object
Method to execute SQL query:
my_cursor.execute("SELECT * FROM my_table")
6. Retrieval results
Use the fetchall()
method of the cursor object to retrieve query results:
results = my_cursor.fetchall()
7. Close the connection
After completion, close the connection to release resources:
my_connection.close()
The above is the detailed content of How to create a new connection in mysql. For more information, please follow other related articles on the PHP Chinese website!