java操作数据库步骤_java数据库操作基本流程
1.java數(shù)據(jù)庫(kù)操作基本流程
a .數(shù)據(jù)庫(kù)連接1.Drivermanager 鏈接數(shù)據(jù)庫(kù)
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鏈接數(shù)據(jù)庫(kù)
String jndi ="jdbc/db"; //??e20-040?9L0-609?數(shù)據(jù)源的名稱
//context是一組名稱到對(duì)象的綁定組成
Hashtable env=new Hashtable ();
Context ctx=(Context)new InitialContext.lookup("env");// 獲得數(shù)據(jù)源所在的上下文點(diǎn)的對(duì)象
DataSource ds=(DataSource)ctx.lookup(jndi);//找到數(shù)據(jù)源
Connection conn=ds.getConnection();//
b.執(zhí)行 sql語(yǔ)句
String sql;
StateMent stat=conn.createStatement();
ResultSet rs=stat.executeQuery(sql);//執(zhí)行數(shù)據(jù)的查詢語(yǔ)句(select);
stat.executeUpdate(sql);//執(zhí)行數(shù)據(jù)的更新語(yǔ)句(inset into ,delete ,update ,drop)
stat.close();
c.用preparedStatement 來(lái)執(zhí)行sql語(yǔ)句
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.處理執(zhí)行結(jié)果
查詢語(yǔ)句,返回記錄集ResultSet對(duì)象
更新語(yǔ)句,返回?cái)?shù)字,表示該更新影響的記錄數(shù)
javax.sql.*
javax.naming.*;
數(shù)據(jù)處理:
1關(guān)閉connection 的自動(dòng)提交
conn.setAutoCommit(false);
2執(zhí)行一系列sql 語(yǔ)句,
Statement sm;
sm=conn.createStatement(sql);
sm.executeUpdate();
sm.close();
3.提交:
conn.commit();
4.回滾機(jī)制;
conn.rollback();
e:線程處理:
D:jndi和dataSource 來(lái)獲得數(shù)據(jù)庫(kù)的鏈接:
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();
}
}
}
};
總結(jié)
以上是生活随笔為你收集整理的java操作数据库步骤_java数据库操作基本流程的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 软件工程毕业设计选题汇总
- 下一篇: MySQL的yum源