Java数据库操作基本流程:取得数据库连接 - 执行sql语句 - 处理执行结果 - 释放数据库连接
1、取得数据库连接
1)用DriverManager取数据库连接,例子:
String className,url,uid,pwd;
className = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:@127.0.0.1:1521:orasvr;
uid = "system";
pwd = "manager";
Class.forName(className);
Connection cn = DriverManager.
getConnection(url,uid,pwd);
2)用jndi(Java的命名和目录服务)方式,例子:
String jndi = "jdbc/db";
Context ctx =
(Context) new InitialContext().lookup
("Java:comp/env");
DataSource ds = (DataSource) ctx.lookup(jndi);
Connection cn = ds.getConnection();
多用于Jsp中
2、执行sql语句
1)用Statement来执行sql语句
String sql;
Statement sm = cn.createStatement();
sm.executeQuery(sql);
// 执行数据查询语句(select)
sm.executeUpdate(sql);
// 执行数据更新语句
(delete、update、insert、drop等)
statement.close();
2)用PreparedStatement来执行sql语句
String sql;
sql = "insert into user (id,name) values (?,?)";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setInt(1,xxx);
ps.setString(2,xxx);
...
ResultSet rs = ps.executeQuery();
// 查询
int c = ps.executeUpdate();
// 更新