Java八股文面试全套真题【含答案】-MySQL数据库+JDBC篇
以下是针对MySQL数据库和JDBC的面试题及其答案:
- JDBC是什么?
答案:JDBC(Java Database Connectivity)是一个标准的Java API,用于在Java程序中连接和执行SQL语句到数据库。
- 使用JDBC连接MySQL数据库的基本步骤是什么?
答案:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "username";
String password = "password";
try {
Connection connection = DriverManager.getConnection(url, user, password);
// 使用connection对象进行数据库操作
System.out.println("Connected to the database successfully");
// 关闭连接
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 如何使用JDBC执行查询并获取结果?
答案:
import java.sql.*;
public class JdbcSelectExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "username";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM tableName")) {
while (resultSet.next()) {
// 获取并打印每一行的数据
System.out.println("Data: " + resultSet.getString("columnName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 如何使用JDBC更新(插入、更新、删除)数据库?
答案:
import java.sql.*;
public class JdbcUpdateExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/databaseName";
String user = "username";
String password = "password";
try (Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement()) {
// 插入操作
statement.executeUpdate("INSERT INTO tableName (column1, column2) VALUES ('value1', 'value2')");
// 更新操作
statement.executeUpdate("UPDATE tableName SET column1 = 'newValue' WHERE column2 = 'value2'");
// 删除操作
statement.executeUpdate("DELETE FROM tableName WHERE column2 = 'value2'");
Syst
评论已关闭