WEB开发网
开发学院数据库Oracle Java实现数据库操作的基本流程 阅读

Java实现数据库操作的基本流程

 2008-09-04 12:49:47 来源:WEB开发网   
核心提示:一、数据库连接 1、Drivermanager链接数据库String className,url,uid,pwd;className="oracle.jdbc.driver.OracleDriver";uid="scott";pwd="tiger";url=&

一、数据库连接

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();//

二、执行sql语句  

String sql;
StateMent stat=conn.createStatement();
ResultSet rs=stat.executeQuery(sql);//执行数据的查询语句(select);
stat.executeupdate(sql);//执行数据的更新语句(inset into ,delete ,update ,drop)
stat.close();

三、用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();

四、处理执行结果

查询语句,返回记录集ResultSet对象

更新语句,返回数字,表示该更新影响的记录数 

javax.sql.*
javax.naming.*; 

数据处理:

1、关闭connection 的自动提交 

conn.setAutoCommit(false);

2、执行一系列sql 语句 

Statementsm;
  sm=conn.createStatement(sql);
  sm.executeupdate();
  sm.close();

3、提交  

conn.commit();

4、回滚机制; 

conn.rollback();

五、线程处理

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();
}
}
}
};

Tags:Java 实现 数据库

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接