Python - 使用mysql-connector-python
首先,确保安装了mysql-connector-python
库:
pip install mysql-connector-python
然后,使用以下代码连接到MySQL数据库:
import mysql.connector
config = {
'user': 'your_username',
'password': 'your_password',
'host': 'your_host',
'database': 'your_database',
'raise_on_warnings': True
}
try:
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
print("Successfully connected to the database.")
# 执行查询等操作...
except mysql.connector.Error as err:
print(f"Error: {err}")
Java - 使用JDBC
首先,添加MySQL JDBC驱动依赖到你的项目中。
使用Maven,添加以下依赖到pom.xml
:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
然后,使用以下代码连接到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:3306/your_database";
String user = "your_username";
String password = "your_password";
try {
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Successfully connected to the database.");
// 执行查询等操作...
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
PHP - 使用mysqli
<?php
$servername = "your_host";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Successfully connected to the database.";
// 执行查询等操作...
?>
Node.js - 使用mysql
首先,确保安装了mysql
库:
npm install mysql
然后,使用以下代码连接到MySQL数据库:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'your_host',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect(error => {
if (error) {
return console.log('Error connecting to the database: ' + error.message);
}
console.log('Successfully connected to the database.');
// 执行查询等操作...
});
C# - 使用MySql.Data
首先,确保安装了MySql.Data
库:
dotnet add package MySql.Data
然后,使用以下代码连接到MySQL数据库:
using System;
using MySql.Data.MySqlClient;
class Program
{
static void Main()
{
string connectionString = "server=your_host;user=your_username;password=your_password;database=your_database;";
using (var connection = new MySqlConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("Successfully connected to the database.");
// 执行查询等操作...
}
catch (MySqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
请注意,上述代码示例中的your_username
、your_password
、your_host
和your_database