江西广告网
标题:
Java数据库操作基本流程
[打印本页]
作者:
shallwesw
时间:
2009-1-16 09:43
标题:
Java数据库操作基本流程
1.Java数据库操作基本流程
a .数据库连接1.Drivermanager 链接数据库 String className,url,uid,pwd; className=\"Oracle.jdbc.driver.OracleDriver\"; uid=\"scott\"; pwd=\"tiger\"; url=\"jdbc
racle:thin
localhost:1521
ra92\"; 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(); } } } };
欢迎光临 江西广告网 (http://bbs.jxadw.com/)
Powered by Discuz! X3.2