The following steps are required to establish a MySQL connection: 1. Import the MySQL client library; 2. Create a connection object; 3. Create a cursor object; 4. Execute the query; 5. Retrieve the results; 6. Close the connection.
How to create a MySQL connection
Establishing a MySQL connection requires the following steps:
1. Import the MySQL client library
First, you need to import the necessary MySQL client library, which provides an interface for the application to communicate with the MySQL database.
For Python:
<code class="python">import mysql.connector</code>
For Java:
<code class="java">import java.sql.*;</code>
2. Create a connection object
Create a connection using the client library Object that will represent a connection to the MySQL database.
For Python:
<code class="python">connection = mysql.connector.connect( host="localhost", user="root", password="my_password", database="my_database" )</code>
host
: The address or hostname of the database server user
: Has a connection Permission usernamepassword
: User’s passworddatabase
: Name of the database to be connectedFor Java:
<code class="java">// 使用 JDBC 创建连接对象 Connection connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/my_database", "root", "my_password" );</code>
3. Create a cursor object
Create a cursor object for executing queries and retrieving results.
For Python:
<code class="python">cursor = connection.cursor()</code>
For Java:
<code class="java">Statement statement = connection.createStatement();</code>
4. Execute the query
Use the cursor object to execute the query and put The results are stored in the result set.
For Python:
<code class="python">cursor.execute("SELECT * FROM my_table")</code>
For Java:
<code class="java">ResultSet resultSet = statement.executeQuery("SELECT * FROM my_table");</code>
5. Retrieval results
Traverse the result set and retrieve individual rows.
For Python:
<code class="python">for row in cursor.fetchall(): print(row)</code>
For Java:
<code class="java">while (resultSet.next()) { System.out.println(resultSet.getInt("id")); }</code>
6. Close the connection
After using the connection, please close the connection object to release resources.
For Python:
<code class="python">cursor.close() connection.close()</code>
For Java:
<code class="java">statement.close(); connection.close();</code>
The above is the detailed content of How to create a connection in mysql. For more information, please follow other related articles on the PHP Chinese website!