如果不用ORM框架,那么直接引入ojdbc6.jar 驱动包,然后在代码中JDBC配置
然后可以使用jdbc实现增删改查,比如下面代码
ResultSet rs = nullStatement stmt = null
Connection conn = null
try {
Class.forName("oracle.jdbc.driver.oracleDriver")
//new oracle.jdbc.driver.oracleDriver()
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.1:1521:yuewei", "scott", "tiger")
stmt = conn.createStatement()
rs = stmt.executeQuery("select * from dept")
while(rs.next()) {
System.out.println(rs.getString("deptno"))
//System.out.println(rs.getInt("deptno"))
}
} catch (ClassNotFoundException e) {
e.printStackTrace()
} catch (SQLException e) {
e.printStackTrace()
} finally {
try {
if(rs != null) {
rs.close()
rs = null
}
if(stmt != null) {
stmt.close()
stmt = null
}
if(conn != null) {
conn.close()
conn = null
}
} catch (SQLException e) {
e.printStackTrace()
}
}
2.
创建数据库了连接
编写数据库 *** 作语句
获取结果
import java.sql.Connection
import java.sql.DriverManager
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
import java.sql.Statement
import java.util.List
import javax.servlet.jsp.jstl.sql.Result
import javax.servlet.jsp.jstl.sql.ResultSupport
public class BaseDao {
private static String driver = "oracle.jdbc.driver.OracleDriver"
private static String url = "jdbc:oracle:thin:@localhost:1521:orcl"
private static String user = "s2"
private static String pwd = "s2"
public static Connection getcon() {
Connection c = null
try {
Class.forName(driver)
c = DriverManager.getConnection(url, user, pwd)
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace()
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return c
}
public static int executeUpdate(String sql,Object...param){
Connection c=getcon()
PreparedStatement p=null
int num=0
try {
p=c.prepareStatement(sql)
if (param!=null) {
for (int i = 0i <param.lengthi++) {
p.setObject(i+1, param[i])
}
}
num=p.executeUpdate()
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}finally{
try {
p.close()
c.close()
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
return num
}
public static Result executeQuery(String sql,Object...param){
Connection c=getcon()
PreparedStatement p=null
ResultSet rs=null
Result r=null
try {
p=c.prepareStatement(sql)
if (param!=null) {
for (int i = 0i <param.lengthi++) {
p.setObject(i+1, param[i])
}
}
rs=p.executeQuery()
r=ResultSupport.toResult(rs)
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}finally{
try {
rs.close()
p.close()
c.close()
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
return r
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)