首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

代码实现mysql数据库连接

MySQL数据库连接的代码实现主要是通过使用编程语言提供的相关库或驱动程序来实现。以下是几种常见编程语言中连接MySQL数据库的代码示例:

  1. Python语言中连接MySQL数据库的代码示例:
代码语言:txt
复制
import mysql.connector

# 建立数据库连接
conn = mysql.connector.connect(
  host="数据库主机地址",
  user="数据库用户名",
  password="数据库密码",
  database="数据库名"
)

# 创建游标对象
cursor = conn.cursor()

# 执行SQL查询
cursor.execute("SELECT * FROM 表名")

# 获取查询结果
results = cursor.fetchall()

# 输出查询结果
for row in results:
    print(row)

# 关闭游标和数据库连接
cursor.close()
conn.close()

推荐的腾讯云产品:云数据库MySQL

  • 链接地址:https://cloud.tencent.com/product/cdb
  1. Java语言中连接MySQL数据库的代码示例(使用JDBC):
代码语言:txt
复制
import java.sql.*;

public class MySQLConnection {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            // 加载MySQL JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            conn = DriverManager.getConnection(
                "jdbc:mysql://数据库主机地址:端口号/数据库名?serverTimezone=UTC",
                "数据库用户名",
                "数据库密码"
            );

            // 创建Statement对象
            stmt = conn.createStatement();

            // 执行SQL查询
            rs = stmt.executeQuery("SELECT * FROM 表名");

            // 处理查询结果
            while (rs.next()) {
                System.out.println(rs.getString("列名"));
            }
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
                if (conn != null) conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

推荐的腾讯云产品:云数据库MySQL

  • 链接地址:https://cloud.tencent.com/product/cdb

以上示例中的数据库连接参数需要根据实际情况进行填写,具体的使用方式和其他编程语言的代码示例可以参考对应的官方文档或相关教程。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券