连接MySQL数据库的语句通常是通过编程语言中的数据库连接库来实现的。以下是几种常见编程语言中连接MySQL数据库的示例代码:
mysql-connector-python
库)import mysql.connector
try:
connection = mysql.connector.connect(
host='localhost',
user='your_username',
password='your_password',
database='your_database'
)
print("Connection successful")
except mysql.connector.Error as err:
print(f"Error: '{err}'")
finally:
if connection.is_connected():
connection.close()
mysql-connector-java
库)import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnectionExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database";
String user = "your_username";
String password = "your_password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection successful");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
mysql
库)const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connection successful');
});
connection.end();
MySql.Data
库)using MySql.Data.MySqlClient;
using System;
class Program
{
static void Main()
{
string connectionString = "Server=localhost;Database=your_database;Uid=your_username;Pwd=your_password;";
try
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("Connection successful");
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
通过以上信息,您应该能够成功连接到MySQL数据库,并解决常见的连接问题。
领取专属 10元无门槛券
手把手带您无忧上云