JDBC
package org.lxh.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class JDBCDemo { public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:MLDN"; public static final String DBUSER = "scott"; public static final String DBPASSWORD = "tiger"; public static void main(String[] args) throws Exception { Connection conn = null; // 数据库连接 Statement stmt = null; // 定义数据库的操作对象 String name = "李四"; int age = 30; String birthday = "1978-09-13"; String note = "不错的人儿!"; Class.forName(DBDRIVER); // 加载驱动程序 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);// 取得连接 stmt = conn.createStatement(); // 创建Statement接口对象 String sql = "INSERT INTO member(mid,name,age,birthday,note)" + " VALUES(member_seq.nextval,'" + name + "'," + age + ",TO_DATE('" + birthday + "','yyyy-mm-dd')," + "'" + note + "') "; System.out.println(sql) ; int len = stmt.executeUpdate(sql); // 执行更新 System.out.println("更新的行数:" + len); stmt.close(); conn.close(); // 关闭数据库连接 } }
分页查询:
public class JDBCDemo { public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver"; public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:MLDN"; public static final String DBUSER = "scott"; public static final String DBPASSWORD = "tiger"; public static void main(String[] args) throws Exception { int currentPage = 3; // 当前在第1页 int lineSize = 5; // 每页显示5条记录 String keyWord = ""; Connection conn = null; // 数据库连接 PreparedStatement pstmt = null; // 定义数据库的操作对象 Class.forName(DBDRIVER); // 加载驱动程序 conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);// 取得连接 String sql = "SELECT * FROM ( " + " SELECT mid,name,age,birthday,note,ROWNUM rn " + " FROM member " + " WHERE (name LIKE ? OR age LIKE ?) AND ROWNUM<=?) temp " + " WHERE temp.rn>? "; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "%" + keyWord + "%"); pstmt.setString(2, "%" + keyWord + "%"); pstmt.setInt(3, currentPage * lineSize); pstmt.setInt(4, (currentPage - 1) * lineSize); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { // 指针向下移动并且判断是否有数据 int mid = rs.getInt(1); String name = rs.getString(2); int age = rs.getInt(3); Date birthday = rs.getDate(4); String note = rs.getString(5); System.out.println(mid + "," + name + "," + age + "," + birthday + "," + note); } conn.close(); // 关闭数据库连接 } }