/** * 获取数据库连接 */ public Connection GetConnection(){ Connection connection=null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); try { connection=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","orcl_test","orcl_test"); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } catch (ClassNotFoundException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return connection; } /** * 添加方法 */ public boolean Add(Student stu){ Connection resConnection = GetConnection(); String insertDataSql=String.format("insert into student(sid, sname, sage, ssex) " + "values (sid_seq.nextval, %s, %s, %s)", "?","?","?"); try { PreparedStatement addStatement = resConnection.prepareStatement(insertDataSql); addStatement.setString(1, stu.getsName()); addStatement.setInt(2, stu.getsAge()); addStatement.setString(3, String.valueOf(stu.getsSex())); int addRes = addStatement.executeUpdate(); addStatement.close(); resConnection.close(); if (addRes>=0) { return true; } else{ return false; } } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } return false; }
jar包:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException;