12 statement = conn.createStatement();
13 String sql = "CREATE TABLE books (id NUMBER(11), title VARCHAR2(64))";
14 statement.execute(sql);
15 } catch (SQLException e) {
16 e.printStackTrace();
17 } finally {
18 try {
19 //为了方便程序的测试,创建后建议删除测试数据。
20 String sql = "drop table books";
21 statement.execute(sql);
22 statment.close();
23 conn.close();
24 } catch (SQLException e) {
25 }
26 }
27 }
3. 插入新的数据。
1 public class MyTest {
2 private static final String EMPLOYEE_TABLE = "create table MyEmployees3 ( "
3 + " id INT PRIMARY KEY, firstName VARCHAR(20), lastName VARCHAR(20), "
4 + " title VARCHAR(20), salary INT " + ")";
5 private static Connection getConnection() throws SQLException,
6 ClassNotFoundException {
7 Class.forName("oracle.jdbc.driver.OracleDriver");
8 Properties conProps = new Properties();
9 conProps.put("user", "sys");
10 conProps.put("password", "helloworld");
11 conProps.put("internal_logon", "sysdba");
12 return DriverManager.getConnection(
13 "jdbc:oracle:thin:@//192.168.1.101:1526/OraHome", conProps);
14 }
15 public static void main(String[] args) throws ClassNotFoundException {
16 Connection conn = null;
17 Statement stmt = null;
18 try {
19 conn = getConnection();
20 stmt = conn.createStatement();
21 stmt.executeUpdate(EMPLOYEE_TABLE);
22 stmt.executeUpdate("insert into MyEmployees3(id, firstName) values(100, 'A')");
23 stmt.executeUpdate("insert into MyEmployees3(id, firstName) values(200, 'B')");
24 System.out.println("main(): table created.");
25 } catch (ClassNotFoundException e) {
26 e.printStackTrace();
27 } catch (SQLException e) {
28 e.printStackTrace();
29 } finally {
30 try {
31 stmt.execute("drop table MyEmployees3");
32 stmt.close();
33 conn.close();
34 } catch (Exception e) {
35 }
36 }
37 }
38 }
3. 数据执行查询语句。
该示例代码主要包括两种常用的查询方式,一种是常量方式,另一种是动态绑定查询条件参数的形式。两者的主要差异为:
通过动态绑定条件的方式进行查询,该方式的查询比直接使用常量的方式性能要高,因为对于很多数据库服务器而言,在多次执行时,都会将下面这种动态绑定参数的sql语句视为同一语句,因此在被提交后,数据库服务器会通过该语句的hash值从解析好的cache中去查找,如果找到匹配的,就不会在对当前语句进行解析,只是带进不同的参数,继续使用原有的语法树直接执行就可以了。相反对于上面那种常量写法,数据库服务器每次都会将其视为新的语句,因此每次都会执行解析过程,从而降低了执行效率,增添了数据库cpu的开销。
1 public class MyTest {
2 private static final String EMPLOYEE_TABLE = "create table MyEmployees3 ( "
3 + " id INT PRIMARY KEY, firstName VARCHAR(20), lastName VARCHAR(20), "
4 + " title VARCHAR(20), salary INT " + ")";
5 private static Connection getConnection() throws SQLExcepti