在Java项目中如何执行SQL查询

2024年06月01日 建站教程

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class ExecuteQuery {
   
  public static void main(String[] args) {
    String url = "jdbc:mysql://localhost:3306/mydatabase";
    String username = "root";
    String password = "password";
     
    try {
      Connection connection = DriverManager.getConnection(url, username, password);
      Statement statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery("SELECT * FROM mytable");
       
      while(resultSet.next()) {
        // 处理查询结果
      }
       
      resultSet.close();
      statement.close();
      connection.close();
    } catch (SQLException e) {
      System.out.println("查询失败原因: " + e.getMessage());
    }
  }
}

本文链接:http://so.lmcjl.com/news/5751/

展开阅读全文
相关内容