import java.sql.*; public class OracleInsertExample { public static void main(String[] args) { String url = "jdbc:oracle:thin:@localhost:1521:XE"; String user = "testuser"; String password = "test123"; Connection conn = null; PreparedStatement stmt = null; try { // Connect to the database conn = DriverManager.getConnection(url,user,password); // Create a prepared statement String sql = "INSERT INTO EMPLOYEES (ID,NAME,SALARY) VALUES (?,?,?)"; stmt = conn.prepareStatement(sql); // Set the parameters stmt.setInt(1,1); stmt.setString(2,"John Smith"); stmt.setDouble(3,50000.00); // Execute the statement stmt.executeUpdate(); System.out.println("Data inserted successfully!"); } catch (sqlException e) { System.out.println("Error: " + e.getMessage()); } finally { try { // Close the statement and connection if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (sqlException e) { System.out.println("Error: " + e.getMessage()); } } } }在上面的示例中,我们首先定义了数据库连接的URL、用户名和密码。然后,我们使用DriverManager类从Oracle数据库获取一个连接对象。接着,我们创建一个PreparedStatement对象,这个对象可以让我们向数据库中插入数据。最后,我们给这个PreparedStatement对象设置参数,并调用executeUpdate()方法来执行插入操作。当操作完成后,我们关闭连接和PreparedStatement对象。 上面的程序只是一个演示示例,实际应用中,我们可能需要更复杂的查询操作。下面是一个更复杂的示例,它从数据库中获取所有员工的名字和工资,并将它们输出到控制台:
import java.sql.*; public class OracleSelectExample { public static void main(String[] args) { String url = "jdbc:oracle:thin:@localhost:1521:XE"; String user = "testuser"; String password = "test123"; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { // Connect to the database conn = DriverManager.getConnection(url,password); // Create a prepared statement String sql = "SELECT NAME,SALARY FROM EMPLOYEES"; stmt = conn.prepareStatement(sql); // Execute the query and get the result set rs = stmt.executeQuery(); // Process the result set while (rs.next()) { String name = rs.getString("NAME"); double salary = rs.getDouble("SALARY"); System.out.println(name + " - " + salary); } } catch (sqlException e) { System.out.println("Error: " + e.getMessage()); } finally { try { // Close the result set,statement and connection if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (sqlException e) { System.out.println("Error: " + e.getMessage()); } } } }在上面的示例中,我们使用相同的方式连接到数据库,并创建一个PreparedStatement对象来执行查询操作。这个查询语句将从EMPLOYEES表中获取所有员工的姓名和工资。我们使用executeQuery()方法来执行这个查询,并将输出结果集中的每一行数据。 这只是Java操纵Oracle数据库的基础,实际应用中有更多的复杂操作和技术。不过,我们希望这篇文章可以帮助你快速开始在Java中使用Oracle数据库。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。