Java代码连接Oracle数据库报错,第三方工具可正常连接求助
Hey Paulino, sorry to hear you’ve been stuck on this for days—let’s break this down step by step since you already confirmed other tools can connect, which narrows our troubleshooting focus.
First, Fix the Critical SQL Bug in Your Delete Method
Before we tackle the connection issue, there’s a syntax error in your deleteCar method that will fail even once you get connected:
// Your broken SQL String sql = "Delete car from which id = ?"; // Corrected version String sql = "DELETE FROM cars WHERE id = ?";
The original query has invalid Oracle SQL syntax—fix this first so you don’t hit another roadblock later.
Troubleshooting the "Network Adapter Could Not Establish Connection" Error
Since SQL Developer and your database dev tool can connect, the issue is likely specific to your Java setup or connection string. Here are the key checks:
1. Verify JDBC Driver Compatibility
Make sure your Oracle JDBC driver (the ojdbc*.jar file in your project) matches your Oracle database version. For example:
- Oracle 12c → Use
ojdbc8.jar - Oracle 19c/21c → Use
ojdbc8.jarorojdbc11.jar
Mismatched drivers often cause silent connection failures, even if other tools work with their own bundled drivers.
2. Adjust Your Connection String Format
Your current string uses the SID format:
"jdbc:oracle:thin:@127.0.0.1:1522:ORCLPJC"
Many modern Oracle setups prefer using the Service Name instead (this is what SQL Developer might be using under the hood). Try switching to this format:
"jdbc:oracle:thin:@//127.0.0.1:1522/ORCLPJC"
Note the double slashes (//) after the @ and a forward slash (/) instead of a colon before the service name. This is more reliable for newer Oracle versions.
3. Explicitly Load the Oracle Driver
While JDBC 4.0+ should auto-load drivers, sometimes explicit loading fixes connection issues. Add this static block to your class to ensure the driver is registered:
static { try { Class.forName("oracle.jdbc.OracleDriver"); // Use the modern driver class } catch (ClassNotFoundException e) { throw new RuntimeException("Failed to load Oracle JDBC Driver", e); } }
4. Fix Resource Management (Bonus Optimization)
Your code creates a new connection every time you call insertCar, updateCar, or deleteCar—this is inefficient and can cause connection leaks. Use a shared connection method and try-with-resources to auto-close connections/streams:
Revised Working Code
Here’s your code with all fixes applied, including connection management and SQL corrections:
import java.sql.*; import oracle.jdbc.OracleDriver; public class Cars { // Follow Java naming conventions: class names start with uppercase private static final String USERNAME = "SYSMAN"; private static final String PASSWORD = "*"; // Updated to Service Name format (try this first) private static final String DB_URL = "jdbc:oracle:thin:@//127.0.0.1:1522/ORCLPJC"; // Explicitly load JDBC driver on class load static { try { Class.forName(OracleDriver.class.getName()); } catch (ClassNotFoundException e) { throw new RuntimeException("Oracle JDBC Driver failed to load", e); } } // Reusable connection method private static Connection getConnection() throws SQLException { return DriverManager.getConnection(DB_URL, USERNAME, PASSWORD); } public static void insertCar(String id, String name, String model, String type) { String sql = "INSERT INTO Cars VALUES(?,?,?,?)"; // Try-with-resources auto-closes conn and pstmt try (Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, id); pstmt.setString(2, name); pstmt.setString(3, model); pstmt.setString(4, type); pstmt.executeUpdate(); } catch (SQLException e) { System.err.println("Insert failed: " + e.getMessage()); e.printStackTrace(); // Print full stack trace for deeper debugging } } public static void updateCar(String type, String id) { // Added space before WHERE to avoid syntax issues from string concatenation String sql = "UPDATE cars SET type = ? WHERE id = ?"; try (Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, type); pstmt.setString(2, id); pstmt.executeUpdate(); } catch (SQLException e) { System.err.println("Update failed: " + e.getMessage()); e.printStackTrace(); } } public static void deleteCar(String id) { // Corrected SQL syntax String sql = "DELETE FROM cars WHERE id = ?"; try (Connection conn = getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, id); pstmt.executeUpdate(); } catch (SQLException e) { System.err.println("Delete failed: " + e.getMessage()); e.printStackTrace(); } } }
Final Checks
If you still hit issues:
- Firewall Verify: Ensure your Java application isn’t blocked by a local firewall (Windows Defender, etc.) from accessing port 1522.
- Listener Status: Run
lsnrctl statusin your terminal to confirm the Oracle listener is running on port 1522 and that theORCLPJCservice is registered.
内容的提问来源于stack exchange,提问作者PaulinoC

