1、创建properties文件
#oracle
#driver=oracle.jdbc.OracleDriver
#url=jdbc\:oracle\:thin\:@localhost\:1521\:xe
#username=system
#password=manager
#mysql
driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://192.168.0.121\:3306/test?user\=root&password\=root&characterEncoding\=utf8
username=root
password=root
2、创建链接数据库类
public class JdbcConnect {
private static Properties prop = new Properties();
static{
try {
//Properties prop = new Properties();
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
Class.forName(prop.getProperty("driver"));
//Class.forName(prop.getProperty("mysqlDriver"));
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Error");
e.printStackTrace();
}
}
public static Connection getConn(){
Connection conn =null;
try {
//Oracle
conn = DriverManager.getConnection(prop.getProperty("url"),
prop.getProperty("username"),prop.getProperty("password"));
//Mysql
//conn = DriverManager.getConnection(prop.getProperty("mysqlUrl"));
//System.out.println(conn);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
return conn;
}
public static void close(Connection conn,PreparedStatement pstmt,ResultSet rs){
try {
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
if(conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
// public static void main(String[] args) {
// new JdbcConnect().getConn();
// }
}
3、测试访问数据库
初始化
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
访问
//查询总记录
public int queryCount() {
int count =0;
try {
conn = MyJdbcConnect.getConn();
// pstmt = conn.prepareStatement("select count(*) from student");
pstmt = conn.prepareStatement("select max(age) as avgvalue from userinfodz");
rs = pstmt.executeQuery();
if(rs.next()){
count = rs.getInt(1);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
MyJdbcConnect.close(conn, pstmt, rs);
}
return count;
}
附:
public interface SQLSentence {
String oinsert="insert into mytable values(mytab_seq.nextval,?,?,?,?,?)";
String minsert="insert into mytable values(null,?,?,?,?,?)";
String update="update mytable t set t.myname=? ,t.myage=?,t.myhobby =?,t.myinfo=? where t.myid=?";
String delete="delete from mytable where myid=?";
String qcount="select count(*) from mytable";
String Pagingfororacle="select * from(select T.*,ROWNUM RN from MyTable T where ROWNUM<=? order by T.myid) where RN>=?";
String Pagingformysql=" select * from mytable limit ? , ?";
String PagingforOracle2 = "select * from(select T.*,ROWNUM RN from MyTable T order by T.myid) where RN between ? and ?";
String GetMyTableById = "select * from mytable where myid = ?";
}