2009年6月8日
最近在学习数据库,无意中找到个连接Oracle的简单的例子,稍微修改了下。特此记录:
1import java.sql.*;
2import java.util.logging.Level;
3import java.util.logging.Logger;
4
5/** *//**
6 * Title: JDBC连接数据库
7 * Description: 本实例演示如何使用JDBC连接Oracle数据库,并演示添加数据和查询数据.
8 */
9public class JDBCExample {
10
11 public static void main(String[] arg) {
12 try {
13 try {
14 //注册JDBC驱动
15 Class.forName("oracle.jdbc.driver.OracleDriver");
16 } catch (ClassNotFoundException ex) {
17 Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, ex);
18 }
19 //创建数据库连接
20 String url = "jdbc:oracle:thin:@127.0.0.1:1521:NEW";
21 String username = "scott";
22 String password = "tiger";
23 Connection con = null;
24 try {
25 con = DriverManager.getConnection(url, username, password);
26 } catch (SQLException ex) {
27 Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, ex);
28 }
29 Statement statement = null;
30 try {
31 statement = con.createStatement();
32 } catch (SQLException ex) {
33 Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, ex);
34 }
35 ResultSet result;
36 //创建表
37 System.out.println("--Creating Tables--");
38 statement.executeUpdate("CREATE TABLE Person(name VARCHAR2(100) PRIMARY KEY,age INTEGER,live_in VARCHAR2(100) )");
39 //插入记录
40 System.out.println("--Inserting Data--");
41 statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES('Robert Bellamy',24,'England')");
42 statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Grayham Downer',null,'Africa')");
43 statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Timothy French',24,'Africa')");
44 statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Butch Fad',53,'USA')");
45 statement.executeUpdate("INSERT INTO Person (name, age, live_in) VALUES ('Judith Brown',34,'Africa')");
46 // 查询
47 System.out.println("--SQL queries--");
48 result = statement.executeQuery("SELECT AVG(age) FROM Person");
49 if (result.next()) {
50 System.out.println("AV.age: " + result.getDouble(1));
51 }
52 System.out.println();
53 result = statement.executeQuery("SELECT name FROM Person WHERE live_in = 'Africa'");
54 System.out.println("All people that live in Africa:");
55 while (result.next()) {
56 System.out.println(" " + result.getString(1));
57 }
58 //删除表
59 statement.execute("DROP TABLE Person");
60 statement.close();
61 con.close();
62 } catch (SQLException ex) {
63 Logger.getLogger(JDBCExample.class.getName()).log(Level.SEVERE, null, ex);
64 }
65 }
66}
发现几个问题:
1.这里任何的SQL语句必须去掉分号,若有分号则会提示java.sql.SQLException: ORA-00911: invalid character的错误。
2.插入语句不能用逗号隔开的形式。如:INSERT INTO Person (name, age, live_in) VALUES ('Butch Fad',53,'USA'), ('Judith Brown',34,'Africa'),"INSERT INTO Person (name, age, live_in) VALUES ('Grayham Downer',null,'Africa')"。
3.NetBeans 6.5里面导入连接Oracle驱动的jar包的步骤是在项目窗口中右键点击“库”,选择添加库将oracle中自带的classes12.jar导入。
posted @
2009-06-08 13:00 杨洋洋 阅读(1235) |
评论 (0) |
编辑 收藏