标签:-- ret oca 性能 try cal product exe ase
之前学习.NET的时候。以前利用ODBC进行连接数据库,而在Java中通常採用JDBC连接数据库,这里以oracle数据库为例简单的总结一下利用JDBC怎样连接并操作数据库。
public class DbUtil {
public static Connection getConnection(){
Connection conn=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");//找到oracle驱动器所在的类
String url="jdbc:oracle:thin:@localhost:1521:bjpowernode"; //URL地址
String username="drp";
String password="drp";
conn=DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
<pre name="code" class="java">
public static void close(PreparedStatement pstmt){
if(pstmt !=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs){
if(rs !=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}}
1、首先找到
D:\oracle\product\10.2.0\db_1\jdbc\lib 找到ojdbc14.jar
2、其次再找到 ojdbc14.jar\oracle\jdbc\driver 以下的oraceldriver这样就找到了要使用的驱动程序文件
public void addUser(User user){
String sql="insert into t_user(user_id,user_name,PASSWORD,CONTACT_TEL,EMAIL,CREATE_DATE)values(?,?
,?,?,?
,?)"; //?为參数占位符
Connection conn=null;
PreparedStatement pstmt=null; //通常利用PreparedStatement进行操作,性能得到优化
try{
conn=DbUtil.getConnection();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, user.getUserId());
pstmt.setString(2,user.getUserName());
pstmt.setString(3, user.getPassword());
pstmt.setString(4, user.getContactTel());
pstmt.setString(5,user.getEmail());
//pstmt.setTimestamp(6,new Timestamp(System.currentTimeMillis()));
pstmt.setTimestamp(6, new Timestamp(new Date().getTime()));//获取当前系统时间
pstmt.executeUpdate();//运行增删改操作
}catch(SQLException e){
e.printStackTrace();
}finally{
DbUtil.close(conn);
DbUtil.close(pstmt);
}
}
public User findUserById(String userId){
String sql = "select user_id, user_name, password, contact_tel, email, create_date from t_user where user_id=?";
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;//定义存放查询结果的结果集
User user=null;
try{
conn=DbUtil.getConnection();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1,userId);
rs=pstmt.executeQuery();//运行查询操作
if(rs.next()){
user=new User();
user.setUserId(rs.getString("user_Id"));
user.setUserName(rs.getString("user_name"));
user.setPassword(rs.getString("password"));
user.setContactTel(rs.getString("contact_Tel"));
user.setEmail(rs.getString("email"));
user.setCreateDate(rs.getTimestamp("create_date"));
}
}catch(SQLException e){
e.printStackTrace();
}finally{
//按顺序进行关闭
DbUtil.close(rs);
DbUtil.close(pstmt);
DbUtil.close(conn);
}
return user;
}
查询方法中用到的ResultSet则与之前用到的DataSet或者DataTable功能类似,这样一联系,似乎这个连接和使用过程变得简单的很多吧!
标签:-- ret oca 性能 try cal product exe ase
原文地址:http://www.cnblogs.com/yutingliuyl/p/6910456.html