1.BaseDao.java
import java.sql.Connection;
import java.sql.DriverManager;
public
class jdbcthin {
static String dbUrl =
"jdbc:oracle:thin:@127.0.0.1:1521:zmp20112859";
//
theUser为数据库用户名
static String theUser = "system";
// thePw为数据库密码
static
String thePw = "zmpandzmp";
//
几个数据库变量
static
Connection con = null;
// 初始化连接
public static
Connection getCon() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//
与url指定的数据源建立连接
con = DriverManager.getConnection(dbUrl, theUser,
thePw);
} catch (Exception e) {
e.printStackTrace();
}
return
con;
}
}
2.test.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import
java.sql.ResultSet;
import
java.sql.SQLException;
public
class test {
/**
* @param args
*/
public
static void main(String[] args) {
Connection con =
BaseDao.getCon();
ResultSet rs =
null;
PreparedStatement ps = null;
String sql = "select sname from
student";
try {
ps = con.prepareStatement(sql);
} catch (SQLException e)
{
System.out.println("預處理異常!");
e.printStackTrace();
}
try
{
rs =
ps.executeQuery();
} catch (SQLException e) {
System.out.println("執行查詢異常!");
e.printStackTrace();
}
try {
while (rs.next()) {
System.out.println("姓名:"
+ rs.getString("sname"));
}
} catch
(SQLException e) {
System.out.println("讀取數據異常!");
e.printStackTrace();
}
}
}