首先创建一个数据库链接类:GetCon
package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class GetCon {
public static final String driver ="oracle.jdbc.driver.OracleDriver";//oracle驱动
public static final String url ="jdbc:oracle:thin:@127.0.0.1:1521:orcl";//url地址
public static final String userName ="wh6y";//用户名
public static final String passWord ="r1";//密码
private static Connection conn;//链接对象
private static GetCon getCon = null;
private GetCon() {
}
public static GetCon getInstance(){//单例模式
if (getCon == null) {
getCon = new GetCon();
}
return getCon;
}
static {
try {
Class.forName(driver);//可以了解一下为什么这么写有个链接http://blog.csdn.net/gaoqida/article/details/61920739?utm_source=itdadao&utm_medium=referral
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void initConnection(){
try {
conn = DriverManager.getConnection(url,userName,passWord);
conn.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getCon(){
initConnection();
return conn;
}
}
新建一个测试类Test2
public class Test2 {
private static StringBuffer sb=new StringBuffer();
public static void main(String[] args) {
String sql="select * from pda_user t ";
Connection con =GetCon.getInstance().getCon();
try {
PreparedStatement prepareStatement = con.prepareStatement(sql);
ResultSet executeQuery = prepareStatement.executeQuery();
while (executeQuery.next()) {
String dbuser = executeQuery.getString(1);
String user_id = executeQuery.getString(2);
String user_name = executeQuery.getString(3);
sb.append("dbuser:"+dbuser+" user_id:"+user_id+" user_name:"+user_name);
System.out.println("dbuser:"+dbuser+" user_id:"+user_id+" user_name:"+user_name);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
数据库内容需要自己添加了
还需要一个classes12.jar放到webroot->web-inf->lib下
Oracle的驱动包,连接Oracle数据库时用的