在上一篇用IDEA进行Java后台开发(二)中我们已经可以成功的调用我们所写的接口,并且做了一些简单的逻辑处理,
由于后台开发离不开数据,所以这篇将进行Servlet于MySQL数据库链接和简单的调用。
1.导包
这里我们选择c3p0和dbutils进行数据库链接,所以导入如下包
这里附上所需jar包下载地址
2.在src根目录下创建c3p0-config.xml文件,进行数据库配置
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 默认配置,c3p0框架默认加载这段默认配置 -->
<default-config>
<!-- 配置JDBC 四个基本属性 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/xiaoxiao</property>
<property name="user">root</property>
<property name="password">Gujianpeng@2018</property>
</default-config> <!-- This app is massive! -->
</c3p0-config>
注:<property name="jdbcUrl">jdbc:mysql://localhost:3306/xiaoxiao</property>中的localhost可以是远程数据库的ip,如果是本地的数据库,就直接用localhost或者本地ip就行了。
3.创建JDBCUtils类
package db;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 将增删改查操作中重复代码提取出来
*/
public class JDBCUtils {
//创建数据库连接池对象
private static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//获取连接的方法
public static Connection getConnection() throws SQLException{
return comboPooledDataSource.getConnection();
}
//提供数据库连接池对象的方法
public static DataSource getDataSource(){
return comboPooledDataSource;
}
//释放资源的方法
public static void release(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
release(stmt, conn);
}
public static void release(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
4.创建要操作表的bean类
package db.bean;
public class UserBean {
private int userId;
private String userPhone;
private String userName;
private String userPwd;
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
5.通过sql语句查表
QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
String sql5 ="select * from contect where userName="+account;
try {
UserBean userBean = runner.query(sql5, new BeanHandler<UserBean>(UserBean.class));
} catch (SQLException e) {
e.printStackTrace();
}
6.完整的Servlet代码
package servlet;
import db.JDBCUtils;
import db.bean.UserBean;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
public class DemoServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* 这里我们只是模拟了一个最简单的业务逻辑,当然,你的实际业务可以相当复杂 */
String account = request.getParameter("account"); // 从 request 中获取名为 account 的参数的值
String password = request.getParameter("password"); // 从 request 中获取名为 password 的参数的值
System.out.println("account:" + account + "\npassword:" + password); // 打印出来看一看
String result = "数据库读取异常!";
if (account.isEmpty()){
result = "用户名为空!";
}else if (password.isEmpty()){
result = "密码为空!";
}else {
QueryRunner runner = new QueryRunner(JDBCUtils.getDataSource());
String sql5 ="select * from contect where userName="+account;
try {
UserBean userBean = runner.query(sql5, new BeanHandler<UserBean>(UserBean.class));
if (userBean != null){
if (password.endsWith(userBean.getUserPwd())){
result = "登陆成功!";
}else {
result = "用户名密码不匹配,登录失败!";
}
}else {
result = "不存在此用户!";
}
} catch (SQLException e) {
e.printStackTrace();
}
}
response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
PrintWriter pw = response.getWriter(); // 获取 response 的输出流
pw.println(result); // 通过输出流把业务逻辑的结果输出
pw.flush();
}
}
7.效果
我们先在表中随便插入几条数据
然后用浏览器直接访问看看
8.遇到的一些问题及解决方法
(1)报错:
Servlet.service() for servlet [DemoServlet] in context with path [] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: com.mchange.v2.ser.Indirector
原因:
使用C3P0数据源时需要依赖 mchange-commons-java-0.2.3.4.jar包。缺少该jar包则会报错!
(2)无法链接服务器中的数据库
登录服务器mysql允许远程链接
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '你的密码' WITH GRANT OPTION;
重载授权表:
FLUSH PRIVILEGES;
退出mysql数据库:
exit
最后,下一篇的链接 用IDEA进行Java后台开发(四)