Java連接MySQL數據庫是常見的開發場景之一,比如查詢數據庫中存儲了多少行數據等。下面是簡單的Java代碼示例,演示了如何使用Java語言來查詢MySQL數據庫中存儲了多少行數據。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class CheckRowCount { 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_db","root","password"); statement = connection.createStatement(); String selectQuery = "SELECT COUNT(*) FROM student"; resultSet = statement.executeQuery(selectQuery); while(resultSet.next()) { int rowCount = resultSet.getInt(1); System.out.println("Number of rows in table: " + rowCount); } } catch (ClassNotFoundException | SQLException ex) { ex.getMessage(); } finally { try { if(statement!=null) { statement.close(); } if(connection!=null) { connection.close(); } } catch(Exception ex) { ex.getMessage(); } } } }
以上是一個簡單的Java應用程序,它連接本地MySQL數據庫,并查詢Test_DB數據庫中student表存儲了多少行數據。