**今天看了一下Servlet的知识,了解了数据如何从客户端传到服务器,我就想用JDBC的知识,把从客户端获得的数据经过服务器处理,操控数据表,但是在请求数据库连接的时候出现了问题
**
数据库连接代码:
public static Connection getConnection() throws Exception {
InputStream is = JDBCutil.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driver = pros.getProperty("driver");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
return connection;
}
服务器处理数据代码:
public class AddServlet extends HttpServlet {
protected 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");
System.out.println(fname);
System.out.println(price);
System.out.println(fcount);
System.out.println(remark);
FruitDAOImpl fruitDAO = new FruitDAOImpl();
Connection connection = null;
try {
connection = JDBCutil.getConnection();
Fruit fruit = new Fruit(1,fname,price,fcount,remark);
fruitDAO.insert(connection,fruit);
System.out.println("insert success");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCutil.closeResource(connection,null);
}
}
前端是一个表单输入数据
服务器可以获取到数据,但是报错,报错位置在我连接数据库的代码上
是这句
//2.加载driver
Class.forName(driver);
但是!我在自己另外写的测试数据库连接的代码中,运行确实成功的,烦请各位指正
@Test
public void testConnection05() throws Exception {
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driver = pros.getProperty("driver");
//2.加载驱动
Class.forName(driver);
//3.获取连接
Connection connection = (Connection) DriverManager.getConnection(url,user,password);
System.out.println(connection);
}
下面是我导入的jar包和我的配置文件
user=root
password=123456
url=jdbc:mysql://localhost:3306/travel?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&serverTimezone=UTC
driver=com.mysql.jdbc.Driver
提前谢谢各位!