达内免费java训练 第八天

今天石成志简单地教了一下怎样在java程序中连接、操作数据库。

1、 操作系统 --> JVM --> .class。 而 java和数据库的关系分三层:
DataBase  :Oracle, SqlServer
DB Driver : 出现过四种: JDBC-ODBC(非跨平台) Bridge -->  ..... --> java network protocal(完全跨平台+网络访问)
JDBC(包括你自己的java代码 + JDBC 的api)

2、 导入jar包
Linux 下改变环境变量 :
vi .bash_profile
CLASSPATH = /home/**soft01/.../**ojdbc14.jar:.:$CLASSPATH  // **号间写成你自己的路径。
export CLASSPATH   // $代表不删除之前的CLASSPATH.
或者在eclipse下导入包: projects-->properties-->JavaBuildPath-->Libraries-->AddExternalJARs

3、驱动不同实现连接不同的数据库。 ojdbc14.jar->oracle.jdbc.driver.OracleDriver
java.sql.*; javax.sql.*;  : // 操作jdbc的java方法
DrvierManager --》加载驱动 & Connection --》 Statement, PreparedStatement, CallableStatement --》ResultSet(如果是查询) --》 Set --》 Web
数据库的连接是有限的,超过后就只能等待。所以数据库需要及时释放连接,用完(得到ResultSet)就断开。  也可以显示调用close().

4、
rs.next()  // 指针往下一行移动,返回值boolean表示是否有下一行。
int i = rs.getInt("id");  // Int 是 "id"( 列名)的类型。
方法都可能抛出异常,SQLException, 而且此异常需要自己处理。若不处理(包括直接throws)。Class.forName() 抛出 ClassNotFoundException.
右键->ShowLineNumbers 显示eclipse的行显示。
Statement stmt = null;
 try {    // 在try外面定义finally里面需要用到的变量。并一定要定义为null,否则错误:未初始化。

5、一些小错误:
ORA-00923: FROM keyword not found where expected  // sql 语句有问题。
ORA-00911: invalid character  //
ClassNotFountException // 需要的jar包不在CLASSPATH中。用2中的两种方法
ORA-02019: connection description for remote database not found  // 因为插入字符串的位置没有加 ''
ORA-00984: column not allowed here    // sql 语法里面字符串用 '' 而不是 "" 包围。
ORA-00001: unique constraint (OPENLAB.SYS_C006595) violated    // 在primary key 里面试图插入重复值。
ORA-00923: FROM keyword not found where expected      // select 的时候没有 from table。
eclipse 中出现 UserInfo cann't be resolved to a type. // 因为另外一个文件UserInfo 没有保存。

6、基本思想:
JDBC 使用步骤:
import java.sql.*;
1)加载驱动;
2)得到连接;
3)得到陈述对象
4)执行操作,得到结果集;
5)操作结果集(循环)
6)关闭(反序: 结果集,陈述对象、连接)
变量声明在try外面声明,这样在finally 中才能用。异常处理。

区分:
 修改 Statement.executeUpdate();
 查询 Statement.executeQuery();

ORM (Object-Oriented + Relationship + Mapping )
 实现映射:  表 ---- 类;  字段(列) ---- 属性;  记录 ---- 对象
一个部门对应多个用户,一个用户对应多个部门。 用集合引用来表示。  而在数据库里表和表之间用键来表示。
 多个记录 ---- 对象的集合

7、 简单代码:
JdbcTest.java:

import java.sql.*;
import java.util.*;

public class JdbcTest{
 public static final String ORACLE_DRIVER = "oracle.jdbc.driver.OracleDriver";
 public static final String URL ="jdbc:oracle:thin:@192.168.0.200:1521:tarena";

                  //jdbc:主协议:子协议:@host:oracle端口:sid
 public static final String USER = "openlab";
 public static final String PASSWORD = "open123";

 
 public static void main( String[] args) throws ClassNotFoundException, SQLException
 {
  JdbcTest jt = new JdbcTest();
  jt.insert(14, "arenaarena", "arenacom");  // 这句话只能做一次
  UserInfo user1 = jt.find(13);
  if( user1 != null ) System.out.println( user1) ;
  else System.out.println( "record not found ! ");
  
  List users = jt.findAll();
  System.out.println( "there are " + users.size() + "be got.");
  Iterator it = users.iterator();
  while( it.hasNext() ){
   user1 = (UserInfo)it.next();
   System.out.println(user1);
  }
 }
 
 public static Connection getCon() {   // 把固定的代码写成函数
  Connection con = null;
  try {
   Class.forName(ORACLE_DRIVER);
   con = DriverManager.getConnection(URL,USER,PASSWORD);
  } catch( ClassNotFoundException e) { e.printStackTrace(); }
   catch ( SQLException e ) { e.printStackTrace(); }
  return con;
 }
 
 public void insert( int id, String name, String email ) {  // 也可以把参数写成 对应类的对象
   Connection conn = getCon();
   Statement stmt = null;
   try{
    stmt = conn.createStatement();
    String sql = "insert into zp_1" +
    "(id, name, email) values" + "("
    + id + ",/'" + name + "/',/'" + email + "/')";   // 注意,因为很容易错,所以可以打印sql检查一下
    
    System.out.println( sql);
    
    stmt.executeUpdate(sql);
    System.out.println( "Insert Table zp successfully . ");
   }catch ( SQLException e ) { e.printStackTrace(); }
   finally {
    if( stmt != null) { try {stmt.close();} catch (SQLException e) {e.printStackTrace(); } }
    if( conn != null) { try {conn.close();} catch (SQLException e) {e.printStackTrace(); } }

   }
   
 }
 
 public UserInfo find( int id ){
  Connection conn = getCon();
  Statement stmt = null;
  ResultSet rs = null;
  UserInfo user = null;    // 声明在外

  try {
   stmt = conn.createStatement();
   String sql = "select id, name, email from zp_1 where id = " + id;
   System.out.println(sql);
   rs = stmt.executeQuery(sql);
   String name, email;
   while( rs.next() ) {
    name = rs.getString("name");
    email = rs.getString("email");
    user = new UserInfo( id, name, email );
    System.out.println( id + "/t" + name + "/t" + email);
   }
  }catch ( SQLException e ) { e.printStackTrace(); }
  finally {
   if( stmt != null) { try {stmt.close();} catch (final SQLException e) {e.printStackTrace(); } }
   if( conn != null) { try {conn.close();} catch (final SQLException e) {e.printStackTrace(); } }
   return user;
  }  
 }
 
 public List findAll() throws ClassNotFoundException, SQLException
 {
  Connection conn = null;
  ResultSet rs = null;
  Statement stmt = null;
  List users = new ArrayList();
  try {
  // 1、加载驱动
  Class.forName(ORACLE_DRIVER);
   
  // 2、得到连接
  conn= DriverManager.getConnection(URL,USER,PASSWORD);
  
  // 3、得到陈述对象
  stmt = conn.createStatement();

  String sql = "select * from zp_1";   // sql 语句后不加 ;
 
  // 4、得到结果集ClassNotFoundException
  rs = stmt.executeQuery(sql);
  
  // 5、操作结果集
  int id;
  String name, email;
  UserInfo user = null;
  while( rs.next()  ) {
   id = rs.getInt("id");
   name = rs.getString("name");
   email = rs.getString("email");
   user = new UserInfo( id, name,email);
   users.add(user);
  }
 }catch ( ClassNotFoundException ce) {
   ce.printStackTrace();
  }catch ( SQLException se) {
   se.printStackTrace();
  } finally {
  // 6、关闭
  if( rs != null )  { try { rs.close(); } catch (SQLException e) {e.printStackTrace(); } }
  if( stmt != null) { try {stmt.close();} catch (SQLException e) {e.printStackTrace(); } }
  if( conn != null) { try {conn.close();} catch (SQLException e) {e.printStackTrace(); } }
  return users;
  }
 }
}

UserInfo.java :

public class UserInfo {
 private int id;
 private String name;
 private String email;
 
 public UserInfo() {
  
 }
 public UserInfo( int id, String name, String email ) {
  this.id = id;    this.name = name;  this.email = email;
 }
 public String toString() {
  return "id = " + id + "name = " + this.name + "email "+ this.email; }

// 用eclipse自动生成get**(), set**().
 public String getEmail() {
  return email;
 }
 public void setEmail(String email) {
  this.email = email;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值