在MySQL数据库中建立连接是一个基本操作,它是进行数据查询、更新、删除等操作的前提,以下是使用MySQL客户端工具和编程语言中建立连接的详细步骤。

使用MySQL命令行工具建立连接
- 打开命令行工具(如Windows的CMD或Git Bash,Linux的终端)。
- 输入以下命令,以启动MySQL客户端:
mysql h 主机名 u 用户名 p
h后跟主机名,指定MySQL服务器所在的主机名或IP地址。u后跟用户名,指定要登录MySQL的用户名。p表示需要输入密码。
输入密码后,会看到类似以下提示:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 1
Server version: 5.7.24log MySQL Community Server (GPL)
这表示连接已经成功建立。
使用编程语言建立连接
Python(使用mysqlconnectorpython)
安装mysqlconnectorpython:
pip install mysqlconnectorpython
编写Python代码:

import mysql.connector
# 连接配置
config = {
'user': '用户名',
'password': '密码',
'host': '主机名',
'database': '数据库名',
'raise_on_warnings': True,
}
# 建立连接
cnx = mysql.connector.connect(**config)
# 创建游标对象
cursor = cnx.cursor()
# 执行查询
cursor.execute("SELECT VERSION()")
# 输出结果
version = cursor.fetchone()
print("Database version : %s " % version)
# 关闭游标和连接
cursor.close()
cnx.close()
Java(使用JDBC)
-
添加MySQL JDBC驱动到项目依赖中。
-
编写Java代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MySQLConnection {
public static void main(String[] args) {
// JDBC URL, username and password of MySQL server
String url = "jdbc:mysql://主机名:端口/数据库名";
String user = "用户名";
String password = "密码";
// Step 2: Register JDBC driver
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
// Step 3: Open a connection
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
// Step 4: Execute a query
Statement statement = null;
try {
statement = connection.createStatement();
String sql = "SELECT VERSION()";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// Retrieve data from result set
String dbVersion = resultSet.getString(1);
System.out.println("Database version : " + dbVersion);
}
} catch (Exception e) {
e.printStackTrace();
}
// Step 5: Cleanup environment
try {
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
常见问题
Q1:连接MySQL数据库时,提示“com.mysql.cj.jdbc.Driver”找不到?
A1: 这通常是因为没有正确添加MySQL JDBC驱动到项目中,请确保已将驱动添加到项目的类路径中,并在代码中通过Class.forName("com.mysql.cj.jdbc.Driver");加载驱动。

**Q2:连接MySQL数据库时,提示“Access denied for user ‘用户名’@’主机名’ (using password: YES)”?
A2: 这意味着提供的用户名或密码错误,请检查用户名和密码是否正确,或者用户是否有权限访问指定的数据库。
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/267237.html