jdbc mysql test
import java.sql.*; public class JdbcMysqlTest { public static void main(String[] args) { Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { // 加載驅動 Class.forName("com.mysql.jdbc.Driver"); // 建立連接 connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); // 創建語句對象 statement = connection.createStatement(); // 執行查詢 resultSet = statement.executeQuery("SELECT * FROM users"); // 處理結果集 while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String password = resultSet.getString("password"); System.out.println("ID: " + id + ", Name: " + name + ", Password: " + password); } } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { // 關閉資源 try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
以上是一個簡單的jdbc連接mysql測試程序,實現了查詢用戶表中的所有記錄并打印輸出。
上一篇mysql #