Home  >  Article  >  Database  >  How to connect to mysql database

How to connect to mysql database

下次还敢
下次还敢Original
2024-04-14 19:12:471088browse

Connecting to the MySQL database requires the following steps: Obtain connection information: server address, port, user name, password, database name. Choose a connection method: You can use a Python library (such as MySQLdb or pymysql) or the command line (such as MySQL). Perform queries and operations: After the connection is established, queries and update operations can be performed. Close connection: After the operation is completed, close the connection to release resources.

How to connect to mysql database

How to connect to MySQL database

Step one: Obtain connection information

  • Server address: the IP address or host name of the database server
  • Port: usually 3306
  • Username: the username of the database user
  • Password: Database user’s password
  • Database name: Name of the database to be connected

Step 2: Select the connection method

  • Use Python library (such as MySQLdb or pymysql):

    <code class="python">import mysql.connector
    
    # 创建连接对象
    conn = mysql.connector.connect(
      host="127.0.0.1",
      port=3306,
      user="username",
      password="password",
      database="database_name"
    )</code>
  • Use command line (such as MySQL):

    <code class="shell">mysql -h 127.0.0.1 -P 3306 -u username -p password database_name</code>

Step 3: Perform queries and operations

Once the connection is established, you can perform queries and operations using:

  • Execute query:

    <code class="python"># 创建游标对象
    cursor = conn.cursor()
    
    # 执行查询
    cursor.execute("SELECT * FROM table_name")
    
    # 获取结果
    rows = cursor.fetchall()
    
    # 关闭游标
    cursor.close()</code>
  • Perform update operation:

    <code class="python">cursor.execute("UPDATE table_name SET field_name='new_value' WHERE condition")
    conn.commit()</code>

Step 4: Close the connection

After the operation is completed, please close the connection to release resources:

<code class="python">conn.close()</code>

The above is the detailed content of How to connect to mysql database. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn