java连接oracle执行sql语句
一个简单的示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class OracleJdbcExample { public static void main(String[] args) { // Oracle数据库的JDBC URL,用户名和密码 String url = "jdbc:oracle:thin:@localhost:1521:orcl"; String username = "your_username"; String password = "your_password"; Connection conn = null; Statement stmt = null; try { // 加载Oracle JDBC驱动程序 Class.forName("oracle.jdbc.driver.OracleDriver"); // 建立连接 conn = DriverManager.getConnection(url, username, password); // 创建Statement对象来执行SQL语句 stmt = conn.createStatement(); // 执行SQL查询并获取结果 String sql = "SELECT * FROM your_table"; ResultSet rs = stmt.executeQuery(sql); // 处理结果 while (rs.next()) { // 根据你的表结构获取数据 int id = rs.getInt("id"); String name = rs.getString("name"); // ... 其他字段 System.out.println("ID: " + id + ", Name: " + name); } // 关闭结果集 rs.close(); // 执行更新操作 String updateSql = "UPDATE your_table SET column_name = 'value' WHERE condition"; int affectedRows = stmt.executeUpdate(updateSql); System.out.println("Affected Rows: " + affectedRows); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { // 关闭Statement和Connection try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } } }