BlogJava 联系 聚合 管理  

Blog Stats

随笔档案

exams


java世界

世界Java

 1.java数据库操作基本流程
a .数据库连接1.Drivermanager 链接数据库
String className,url,uid,pwd;
className="oracle.jdbc.driver.OracleDriver";
uid="scott";
pwd="tiger";
url="jdbc:oracle:thin:@localhost:1521:ora92";
Class.forName(classname);
Connection conn=DriverManager.getConnection(url,uid,pwd);
2.JNDI链接数据库
String jndi ="jdbc/db"; //  e20-040 9L0-609 数据源的名称
//context是一组名称到对象的绑定组成
Hashtable env=new Hashtable ();
Context ctx=(Context)new InitialContext.lookup("env");// 获得数据源所在的上下文点的对象
DataSource ds=(DataSource)ctx.lookup(jndi);//找到数据源

Connection conn=ds.getConnection();//
b.执行 sql语句
String sql;
StateMent stat=conn.createStatement();
ResultSet rs=stat.executeQuery(sql);//执行数据的查询语句(select);
stat.executeUpdate(sql);//执行数据的更新语句(inset into ,delete ,update ,drop)
stat.close();
c.用preparedStatement 来执行sql语句
String sql="inset into table(id,name) values(?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setInt(1,001);
ps.setString(2,"zhangmanli");


 

ps.executeQuery();
int count=ps.executeUpdate();
d.处理执行结果
查询语句,返回记录集ResultSet对象
更新语句,返回数字,表示该更新影响的记录数
javax.sql.*
javax.naming.*;
数据处理:
1关闭connection 的自动提交
conn.setAutoCommit(false);
2执行一系列sql 语句,
Statement sm;
sm=conn.createStatement(sql);
sm.executeUpdate();
sm.close();


 

3.提交:
conn.commit();
4.回滚机制;
conn.rollback();
e:线程处理:
D:jndi和dataSource 来获得数据库的链接:
import java.sql.ResultSet ;
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;


 

import java.util.Hashtable;
import java.util.Properties;
import java.io.*;
public class BasicExample{


 

{
 public static void main(String args[]){
  Connection conn=null;
  try{
   Properties prop =new Properties();
   prop.load(new FileInputStream("simple.properties"));


 


   Hashtable env =new Hashtable();
   env.put(Context.INITIAL_CONTEXT_FACTORY,prop.getProperty("INITIAL_CONTEXT_FACTORY"));
   env.put(Context.PROVIDER_URL,prop.getProperty("PROVIDER_URL"));
   InitialContext ctx=new InitialContext(env);


 

   DataSource ds=(DataSource)ctx.lookup("Book");
   Conn=ds.getConnection();
   Statement stat=conn.createStatement();;
   ResultSet rs=stmt.executeQuery(sql);
   while(rs.next()){
    int id=Integer.parseInt(rs.getString("userId"));
    String userName=rs.getString ("username");
   }
  }catch(SQLException e){
   e.printStackTrace();
  }finally{
   try{
    if(conn!=null){
     conn.close();
    }
   }catch(SQLException e){
    e.printStackTrace();
   }
  }
 }


 

};

posted on 2007-09-27 11:02 java2java 阅读(708) 评论(3)  编辑  收藏

评论

# re: java数据库操作基本流程 2007-09-27 11:29 千里冰封
对于初学数据库的人是挺有帮助的  回复  更多评论
  

# re: java数据库操作基本流程 2007-09-27 11:52 CoderDream
很基础的东西建议放到新手区!  回复  更多评论
  

# re: java数据库操作基本流程 2007-09-27 19:17 千里冰封
呵呵,现在已经放到新手区了  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: