本帖最后由 柳雷 于 2012-7-26 16:24 编辑
public class JDBCUtil {
private static String driver = "";
private static String url = "";
private static String dbUser = "";
private static String dbPassword = "";
public static void getParam(){
String filename = "src/database.properties";
File file = new File(filename);
try {
FileInputStream fis = new FileInputStream(file);
Properties props = new Properties();
props.load(fis);
driver = props.getProperty("driver");
url = props.getProperty("url");
dbUser = props.getProperty("dbUser");
dbPassword = props.getProperty("dbPassword");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
getParam();
Connection conn = null;
try{
Class.forName(driver);
conn = DriverManager.getConnection(
url,dbUser,dbPassword);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
Connection conn = JDBCUtils.getConnection();
System.out.println("连接:"+conn);
}
}
模仿别人写了个JDBC的工具类,获取连接。本身这个工具类没有问题,执行main方法结果如下:
连接:com.mysql.jdbc.Connection@1808199
但是我发布服务到web项目上,却出错了
servlet关键代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserDao userDao = new UserDao();
String errorInfo = "";
String loginName = request.getParameter("loginName");
String password = request.getParameter("password");
User user = userDao.selectUserByName(loginName);
dao代码如下:
public User selectUserByName(String name){
User user = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from user where name = ?";
try {
conn = JDBCUtil.getConnection();
System.out.println("#########获取连接:"+conn);
ps = conn.prepareStatement(sql);
报错如下:
java.io.FileNotFoundException: src\database.properties (系统找不到指定的路径。)
#########获取连接:null
意思是取不到路径,是不是因为发布到tomcat服务器,所以src/database.properties就取不到了?我应该怎么写呢?怎么才能取到这个配置文件中的内容呢? |