以下是一個簡單的JDBC查詢數據庫的代碼示例:
import java.sql.*; public class JdbcQueryExample {????public?static?void?main(String[]?args)?{
????????//?JDBC連接信息
????????String?url?=?“jdbc:mysql://localhost:3306/mydatabase”;
????????String?username?=?“root”;
????????String?password?=?“password”;
????????
????????//?SQL查詢語句
????????String?query?=?“SELECT?*?FROM?mytable”;
????????
????????try?{
????????????//?加載JDBC驅動程序
????????????Class.forName(“com.mysql.jdbc.Driver”);
????????????
????????????//?建立數據庫連接
????????????Connection?connection?=?DriverManager.getConnection(url,?username,?password);
????????????
????????????//?創建Statement對象
????????????Statement?statement?=?connection.createStatement();
????????????
????????????//?執行查詢
????????????ResultSet?resultSet?=?statement.executeQuery(query);
????????????
????????????//?處理查詢結果
????????????while?(resultSet.next())?{
????????????????int?id?=?resultSet.getInt(“id”);
????????????????String?name?=?resultSet.getString(“name”);
????????????????int?age?=?resultSet.getInt(“age”);
????????????????System.out.println(id?+?",?"?+?name?+?",?"?+?age);
????????????}
????????????
????????????//?關閉結果集、Statement和連接
????????????resultSet.close();
????????????statement.close();
????????????connection.close();
????????}?catch?(ClassNotFoundException?|?SQLException?e)?{
????????????e.printStackTrace();
????????}
????} }
這個例子假設你已經安裝并配置了MySQL數據庫,并且在本地主機上運行。可以根據實際情況修改連接URL、用戶名和密碼。查詢語句可以根據你的表結構修改。