连接MySQL数据库的代码可以使用不同编程语言编写,以下是一些示例:
import mysql.connector
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'your_host',
'database': 'your_database'
}
try:
conn = mysql.connector.connect(**config)
print("Connected to MySQL database")
# Perform database operations here
except mysql.connector.Error as error:
print(f"Failed to connect to MySQL database: {error}")
finally:
if conn.is_connected():
conn.close()
print("Disconnected from MySQL database")
相关产品推荐:腾讯云云数据库MySQL,产品介绍链接:https://cloud.tencent.com/product/cdb_mysql
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://your_host/your_database";
String username = "your_username";
String password = "your_password";
try {
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected to MySQL database");
// Perform database operations here
conn.close();
System.out.println("Disconnected from MySQL database");
} catch (SQLException e) {
System.out.println("Failed to connect to MySQL database: " + e.getMessage());
}
}
}
相关产品推荐:腾讯云云数据库MySQL,产品介绍链接:https://cloud.tencent.com/product/cdb_mysql
<?php
$servername = "your_host";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to MySQL database\n";
// Perform database operations here
$conn = null;
echo "Disconnected from MySQL database\n";
} catch(PDOException $e) {
echo "Failed to connect to MySQL database: " . $e->getMessage();
}
?>
相关产品推荐:腾讯云云数据库MySQL,产品介绍链接:https://cloud.tencent.com/product/cdb_mysql
require 'mysql2'
client = Mysql2::Client.new(
:host => "your_host",
:username => "your_username",
:password => "your_password",
:database => "your_database"
)
begin
puts "Connected to MySQL database"
# Perform database operations here
ensure
client.close
puts "Disconnected from MySQL database"
end
相关产品推荐:腾讯云云数据库MySQL,产品介绍链接:https://cloud.tencent.com/product/cdb_mysql
这些示例代码可根据实际情况进行修改,包括替换为您的MySQL数据库的主机地址、用户名、密码和数据库名称。同时,相关产品推荐是腾讯云云数据库MySQL,您可以点击链接查看该产品的详细介绍和功能特点。
领取专属 10元无门槛券
手把手带您无忧上云