1.关于找不到输入流的问题
要使用当前类加载器
即由
InputStream is=ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
改为
InputStream is= JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
2.关于配置文件的位置
不用放到奇奇怪怪的文件夹下边,直接放到src文件夹下就可以使用
3.关于jar包的导入问题
不能只导入到src中,还要将需要使用的jar包导入到Artifacts中去:file-project structure-Artifacts
全部代码:
package servlet;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.util.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
class Fruit{
String fname;
int price;
int fcount;
String remark;
public Fruit(){}
public Fruit(String fname,int price,int fcount,String remark){
this.fname=fname;
this.fcount=fcount;
this.price=price;
this.remark=remark;
}
}
public class DAO {
public static Connection druidConnection() throws Exception {
DataSource source=null;
Properties pros=new Properties();
// BufferedReader is = new BufferedReader(new FileReader("druid.properties"));
InputStream is= JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pros.load(is);
source= DruidDataSourceFactory.createDataSource(pros);
Connection conn= source.getConnection();
System.out.println("数据库连接成功");
return conn;
}
public static void fruitUpdate(Fruit fruit,Connection conn) throws SQLException {
QueryRunner runner=new QueryRunner();
String sql="insert into fruit(fname,price,fcount,remark) values(?,?,?,?)";
int count=runner.update(conn,sql,fruit.fname,fruit.price,fruit.fcount,fruit.remark);
System.out.println("添加了"+count+"条记录");
}
}
package servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
public class AddServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fname=req.getParameter("fname");
String priceStr=req.getParameter("price");
Integer price=Integer.parseInt(priceStr);
String fcountStr=req.getParameter("fcount");
Integer fcount=Integer.parseInt(fcountStr);
String remark=req.getParameter("remark");
Fruit fruit=new Fruit(fname,price,fcount,remark);
Connection conn=null;
try {
conn=DAO.druidConnection();
DAO.fruitUpdate(fruit,conn);
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
if(conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
// System.out.println(fname);
// System.out.println(price);
// System.out.println(fcount);
// System.out.println(remark);
}
}