“java,import java.sql.Connection;,import java.sql.DriverManager;,import java.sql.SQLException;,,public class MySQLConnection {, public static void main(String[] args) {, String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC";, String user = "用户名";, String password = "密码";,, try {, Class.forName("com.mysql.cj.jdbc.Driver");, Connection connection = DriverManager.getConnection(url, user, password);, System.out.println("连接成功");, connection.close();, } catch (ClassNotFoundException e) {, e.printStackTrace();, } catch (SQLException e) {, e.printStackTrace();, }, },},
“
以下是使用Java连接MySQL数据库的详细代码,包括小标题和单元表格:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class MySQLConnectionDemo { public static void main(String[] args) { // 加载驱动 try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } // 连接数据库 String url = "jdbc:mysql://localhost:3306/数据库名?useSSL=false&serverTimezone=UTC"; String user = "用户名"; String password = "密码"; Connection connection = null; try { connection = DriverManager.getConnection(url, user, password); System.out.println("数据库连接成功!"); } catch (SQLException e) { e.printStackTrace(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } // 执行查询操作 String query = "SELECT * FROM 表名"; Statement statement = null; ResultSet resultSet = null; try { statement = connection.createStatement(); resultSet = statement.executeQuery(query); while (resultSet.next()) { System.out.println("字段1:" + resultSet.getString("字段1") + ",字段2:" + resultSet.getString("字段2")); } } catch (SQLException e) { e.printStackTrace(); } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
请将上述代码中的数据库名
、用户名
、密码
、表名
和字段1
、字段2
等替换为实际的值。
评论(0)