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:
<code class="python">import mysql.connector my_connection = mysql.connector.connect( host="localhost", user="root", password="my_password", database="my_database", )</code>
3. Verify the connection
Check whether the connection object is successfully established, you can use theis_connected()
function:
<code class="python">if my_connection.is_connected(): print("连接成功!") else: print("连接失败。")</code>
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:
<code class="python">my_cursor = my_connection.cursor()</code>
5. Execute the query
Use the execute() of the cursor object
Method to execute SQL query:
<code class="python">my_cursor.execute("SELECT * FROM my_table")</code>
6. Retrieval results
Use the fetchall()
method of the cursor object to retrieve query results:
<code class="python">results = my_cursor.fetchall()</code>
7. Close the connection
After completion, close the connection to release resources:
<code class="python">my_connection.close()</code>
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!