7、Java纯jdbc连接
一、导入jdbc包,这里采用5.1.16版本
二、开始jdbc梦幻联动
首先开始的创建全局变量
1)加载驱动、获取连接,写在一个方法里面getConnection(数据库名,连接名,连接密码)
//加载驱动、获取链接 public static Connection getConnection() { try { Class.forName("com.mysql.jdbc.Driver");//加载驱动 con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/"+databaseName,root,password); } catch (Exception e) { e.printStackTrace(); } return con; }
2)创建prepareStatement,使用sql语句并使用ResultSet 接收,注意prepareStatement中的方法下标是从1开始的。
public static ResultSet query(String sql,Object[] obj) { try { con = getConnection(); //创建prepareStatement pst = con.prepareStatement(sql); if(obj != null) { for (int i = 0; i < obj.length; i++) { //给sql里需要的数据进行注入值 pst.setObject(i+1, obj[i]); } } //int rs=pst.execute();增删查改使用 rs = pst.executeQuery();//执行查询sql } catch (Exception e) { e.printStackTrace(); } return rs; }
3)再使用5、6的技术从前端传值到后端并在BaseServlet
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>ajax登陆页面</title> </head> <body> <span>账号</span><input type="text" name="username"> <span>密码</span><input type="text" name="password"> <button>登陆</button> <script src="js/jquery-3.6.0.min.js"></script> <script> $("button").click(function(){ var username = $("input[name='username']").val(); var password = $("input[name='password']").val(); $.ajax({ url:"user?method=login", //请求地址 type:"get", //请求方式 data:{ //前端给后台发送的参数 username:username, password:password }, dataType:"json", //后台给前端返回参数的格式 success:function(result){ //result后台给前端响应的参数 if(result.status == true){ location.href = "index.jsp"; }else{ alert(result.message); } } }); }); </script> </body> </html>
package com.cqkj.controller; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSON; import com.cqkj.utils.JDBCDemo; import com.cqkj.utils.ResultMap; @WebServlet("/user") public class UserServlet extends BaseServlet{ //servlet是什么? 哪个类继承了HttpServlet,那么这个类就不再是类而是servlet ResultMap resultMap = new ResultMap(); JDBCDemo jd = new JDBCDemo(); public String login(HttpServletRequest req, HttpServletResponse resp) { String username = req.getParameter("username"); String password = req.getParameter("password"); String sql = "select * from user where username = ? and password = ?"; Object[] obj = {username,password}; ResultSet rs = jd.query(sql, obj); try { if(rs.next()) { resultMap.setStatus(true); }else { resultMap.setStatus(false); resultMap.setMessage("用户名输入有误!"); } } catch (SQLException e) { e.printStackTrace(); } String jsonStr = JSON.toJSONString(resultMap); return jsonStr; } }