首先是工具类:
package com.fill.jweb_jdbc_new;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
/**
*
* @author liufeihong
*数据库操作工具类
*/
public class dbutils {
public static String URL;
public static String USERNAME;
public static String PWD;
public static String DRIVER;
private static ResourceBundle rb=ResourceBundle.getBundle("com.fill.jweb_jdbc_new.db-config");
//防止工具类被实例化
private dbutils(){}
//保证只加载一次的东西
static{
//读配置文件
URL=rb.getString("jdbc.url");
USERNAME=rb.getString("jdbc.user");
PWD=rb.getString("jdbc.pwd");
DRIVER=rb.getString("jdbc.DRIVER");
//加载驱动
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//获取数据库连接
public static Connection getConnection(){
Connection conn=null;
try {
conn=(Connection) DriverManager.getConnection(URL, USERNAME, PWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("获取连接失败");
}
return conn;
}
public static void close(Statement sta,ResultSet re,Connection conn){
try {
if(sta!=null)
sta.close();
if(re!=null)
re.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
属性文件:
db-config.properties
jdbc.url=jdbc:mysql://127.0.0.1:3308/test
jdbc.user=root
jdbc.pwd=root
jdbc.DRIVER=com.mysql.jdbc.Driver
下面开始测试:
package com.fill.jweb_jdbc_new;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class Test {
public static void findAll(){
//通过工具类获取数据库连接
PreparedStatement ps=null;
ResultSet rs=null;
Connection conn=dbutils.getConnection();
String sql="select * from test where id>0";
try {
ps=(PreparedStatement) conn.prepareStatement(sql);
rs=ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("name")+"<br>");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dbutils.close(ps, rs, conn);
}
}
public static void main(String[] args) {
findAll();
}
}