项目执行难题:Java与MySQL数据交互示例

原创 柔光的暖阳◎ 2024-10-06 15:18 100阅读 0赞

在项目执行中,Java与MySQL的数据交互是一个常见的挑战。以下提供一个简单的示例来说明这个问题:

  1. Java连接MySQL
    ```java
    import java.sql.Connection;
    import java.sql.DriverManager;

public class DatabaseConnection {
private static final String DB_URL = “jdbc:mysql://localhost:3306/mydatabase”;
private static final String USER = “username”;
private static final String PASS = “password”;

  1. public static Connection getConnection() {
  2. try {
  3. return DriverManager.getConnection(DB_URL, USER, PASS));
  4. } catch (Exception e) {
  5. System.out.println("Error while connecting to the database: " + e.getMessage());
  6. e.printStackTrace();
  7. }
  8. return null;
  9. }

}

  1. 2. **Java操作MySQL**(例如查询数据):
  2. ```java
  3. import java.sql.ResultSet;
  4. import java.sql.Statement;
  5. public class DatabaseUsage {
  6. public static void main(String[] args) {
  7. Connection connection = DatabaseConnection.getConnection();
  8. try (Statement stmt = connection.createStatement();
  9. ResultSet rs = stmt.executeQuery("SELECT * FROM my_table")) {
  10. // Iterate over the results
  11. while (rs.next()) {
  12. int id = rs.getInt("id");
  13. String name = rs.getString("name");
  14. System.out.println("ID: " + id + ", Name: " + name);
  15. }
  16. } catch (Exception e) {
  17. System.out.println("Error while operating with the database: " + e.getMessage());
  18. e.printStackTrace();
  19. } finally {
  20. if (connection != null) {
  21. try {
  22. connection.close();
  23. } catch (Exception e) {
  24. System.out.println("Error closing database connection: " + e.getMessage());
  25. e.printStackTrace();
  26. }
  27. }
  28. }
  29. }
  30. }

上述示例展示了如何使用Java连接MySQL数据库,并进行数据查询操作。在实际项目中,可能需要处理更复杂的数据交互和事务管理。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,100人围观)

还没有评论,来说两句吧...

相关阅读