概述
链接数据库
DBConnection.java代码:
package com.qcby.db;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public static void main(String[] args) {
}
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/wy2022?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false";
String user = "root";
String password = "2020";
public Connection conn;
public DBConnection() {
try {
Class.forName(driver);
conn = (Connection) DriverManager.getConnection(url, user, password);//
// if(!conn.isClosed())
// System.out.println("Succeeded connecting to the Database!");
} catch (Exception e) {
e.printStackTrace();
}
}
public void close() {
try {
this.conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
JDBC
MysqlUtil.java代码:
package com.qcby.db;
import java.rmi.StubNotFoundException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MysqlUtil {
public static void main(String[] args) {
/*String sql = "insert into t_student(name,age,sex) values("张三",21,"男")";
System.out.println(add(sql));*/
/*String sqldel = "delete from gq_user where id=11";
System.out.println(del(sqldel));*/
/*String sqlupdate ="update gq_user set age = 30 where username="gs1"";
System.out.println(update(sqlupdate));*/
/*String sql = "select count(*) from gq_user";
System.out.println(getCount(sql));*/
/*String[] col = {"id","name","age"};
String sql = "select * from t_student";
String sqlCount = "select count(*) from t_student";
String strJson = getJsonBySql(sqlCount,sql,col);
System.out.println(strJson);*/
/*String sqlcount = "select count(*) from gq_user";
String sql="select * from gq_user";
String[] col = {"username","age","id","sex","salary"};
System.out.println(getJsonBySql(sqlcount, sql, col));*/
/*String sql = "select * from t_user";
String[]
column = {"id","username","password","available"};
ArrayList<String[]> strings = MysqlUtil.showUtil(sql, column);
for (String[] string : strings) {
System.out.println(Arrays.toString(string));
}*/
}
/*添加*/
public static int add(String sql) {
// System.out.println("sql语句是:" + sql);
int i=0;
//数据库连接
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
preStmt.executeUpdate();
preStmt.close();
db.close();//关闭连接
i = 1;
System.out.println("数据插入成功,sql语句是:" + sql);
} catch (Exception e) {
e.printStackTrace();
}
return i;//返回影响的行数,1为执行成功;
}
/*修改数据*/
public static int update(String sql) {
int i =0;
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
preStmt.executeUpdate();
preStmt.close();
db.close();
i = 1;
System.out.println("数据更新成功,sql语句是:" + sql);
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}
/*删除*/
public static int del(String delstr) {
int i=0;
DBConnection db = new DBConnection();
try {
PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(delstr);
preStmt.executeUpdate();
preStmt.close();
db.close();
i = 1;
System.out.println("数据删除成功,sql语句是:" + delstr);
} catch (SQLException e){
e.printStackTrace();
}
return i;
}
/*查询数量*/
public static int getCount(String sql) {
int sum = 0;
DBConnection db = new DBConnection();
try {
Statement stmt = (Statement) db.conn.createStatement();
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
while (rs.next()) {
sum += rs.getInt(1);
}
rs.close();
db.close();
} catch (Exception e) {
// TODO: handle exception
}
return sum;
}
/**
*功能描述 查询json数据
* @author 郭帅
* @date 2021-03-22 10:30
* @param sqlcount 查询数量的sql
* @param sql 查询具体数据的sql
* @param colums 查询的字段
* @return java.lang.String
*/
public static String getJsonBySql( String sqlcount,String sql,String[] colums){
int count = getCount(sqlcount);
System.err.println("标红信息展示sql:" + sql);
ArrayList<String[]>
result = new ArrayList<String[]>();
DBConnection db = new DBConnection();
try {
Statement stmt = (Statement) db.conn.createStatement();
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
while(rs.next()){
String[] dataRow = new String[colums.length];
for( int i = 0; i < dataRow.length; i++ ) {
dataRow[i] = rs.getString( colums[i] );
}
result.add(dataRow);
}
rs.close();
db.close();//
} catch (SQLException e) {
e.printStackTrace();
}
return listToJson(result,colums,count);
}
/**
*功能描述 查询数据
* @author 郭帅
* @date 2021-03-22 10:38
* @param sql 查询具体数据的sql
* @param colums
查询的字段
* @return java.util.ArrayList<java.lang.String[]>
*/
public static ArrayList<String[]> showUtil( String sql, String[] colums){
ArrayList<String[]>
result = new
ArrayList<String[]>();
DBConnection db = new DBConnection();
try {
Statement stmt = (Statement) db.conn.createStatement();
ResultSet rs = (ResultSet) stmt.executeQuery(sql);
while(rs.next()){
String[] dataRow = new String[colums.length];
for( int i = 0; i < dataRow.length; i++ ) {
dataRow[i] = rs.getString( colums[i] );
}
result.add(dataRow);
}
rs.close();
db.close();//
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
/**
* 转化为json数据字符串
* @param
* @return
*/
public static String listToJson( ArrayList<String[]> list,String[] colums,int count) {
String jsonStr = "{"code":0,"msg":"成功了","count":"+count+","data":[";
for(int i = 0; i < list.size(); i++) {
String arr = "{";
for( int j = 0; j < list.get(0).length; j++) {
if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
arr += """ + colums[j] + "":""";
}else {
arr += """ + colums[j] + """+":" ;
arr +=
""" + list.get(i)[j].replace(""","\"") + """;
}
if( j < list.get(0).length - 1 ) {
arr += ",";
}
}
arr += "}";
if( i < list.size() - 1 ) {
arr += ",";
}
jsonStr += arr;
}
jsonStr += "]}";
return jsonStr;
}
}
前端部分
login.html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 导入的为本地文件,如果没有则将下方代码修改为 ()-->
<!-- <scriptsrc="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> -->
<script src="/wy2022/resource/js/jquery.min.js"></script>
</head>
<script type="text/javascript">
//文档就绪函数,文档就绪了在执行
$(function(){
$(".btn").click(function(){
var account = $(".account").val();
var password = $(".password").val();
//发起请求
$.ajax({
url:"/wy2022/login",
type:"post",
data:{
"account":account,
"password":password
},
success:function(data){
console.log(data)
if(data.code==0){//登陆失败
alert(data.msg)
}else{//登陆成功
alert(data.msg)
location.href = "/wy2022/content.html"
}
},
error:function(){
alert("请联系管理员");
}
})
})
})
</script>
<body>
账号:<input type="text" class="account" ><br><br>
密码:<input type="password" class="password"><br><br>
<input type="button" value="登录" class="btn">
</body>
</html>
content.html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 导入的为本地文件,如果没有则将下方代码修改为 ()-->
<!-- <scriptsrc="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> -->
<script src="/wy2022/resource/js/jquery.min.js"></script>
</head>
<body onload="get()">
账号:<input type="text" class="account" ><br><br>
密码:<input type="password" class="password"><br><br>
<input type="button" value="注册"
class="btn" onclick="insert()">
<div id="inf">
</div>
<div style="display:none;background-color:red" id="up_div">
id:<input type="text" name="id" class="up_id" ><br><br>
账号:<input type="text" class="up_account" ><br><br>
密码:<input type="password" class="up_password"><br><br>
<input type="button" value="修改"
class="btn" onclick="update()">
</div>
</body>
<script type="text/javascript">
function get(){
$.ajax({
url:"/wy2022/search",
data:{},
type:"get",
success:function(value){
console.log(value.data);
ViewList(value.data);
}
});
}
//创建一个表格,里边存入有后台传输过来的消息,并在div中打印出来
function ViewList(value){
console.log(value);
var html = '<table style="border:1px, solid #000;width:300px;height:20px;">';
for(var i = 0;i<value.length;i++){
html += '<tr>';
html += '<td style="border:1px solid #000;width:30px;height:20px;" id="td_type">'+ value[i].id + '</td>';
html += '<td style="border:1px solid #000;width:30px;height:20px;" id="td_type">'+ value[i].account + '</td>';
html += '<td style="border:1px solid #000;width:60px;height:20px;" id="td_type">'+ value[i].password + '</td>';
html += '<td style="border:1px solid #000;width:135px;height:20px;">';
html += '<input style="border:1px solid #000;width:40px;height:20px;" id="td_type" type="submit" value="修改" οnclick="updateDiv(' + value[i].id + ')"/>';
html += '<input style="border:1px solid #000;width:40px;height:20px;" id="td_type" type="submit" value="删除" οnclick="del(' + value[i].id + ')"/>';
html += '</td>';
html += '</tr>';
}
html += '</table>';
$("#inf").empty().append(html);
}
function insert(){
var account = $(".account").val();
var password = $(".password").val();
$.ajax({
url:"/wy2022/InsertServlet",
data:{"account":account,"password":password},
success:function(value){
console.log(value);
}
});
}
function updateDiv(id){
document.getElementById("up_div").style.display = "block";
$(".up_id").val(id);
}
function del(id){
$.ajax({
url:"/wy2022/DeleteServlet",
data:{"id":id},
type:"get",
success:function(value){
console.log(value);
}
});
}
function update(){
var id = $(".up_id").val();
var account = $(".up_account").val();
var password = $(".up_password").val();
$.ajax({
url:"/wy2022/UpdateServlet",
data:{"id":id,"account":account,"password":password},
success:function(value){
console.log(value);
}
});
}
</script>
</html>
servlet部分
LoginServlet.java代码:
package com.qcby.servlet;
import java.io.IOException;
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.qcby.db.MysqlUtil;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决中文乱码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
//接受数据
String account = request.getParameter("account");
String password = request.getParameter("password");
//查询数据库
String sql = "select count(*) from admin where account='"+account+"' and password='"+password+"'";
int res = MysqlUtil.getCount(sql);
System.out.println(res);
//根据查询数据库的结果准备给前端返回数据
String json="{"code":0,"msg":"登录失败"}";
if (res!=0) {
json = "{"code":1,"msg":"登录成功"}";
}
//给前端响应数据
response.getWriter().write(json);
}
}
SearchServlet.java代码:
package com.qcby.servlet;
import java.io.IOException;
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.qcby.db.MysqlUtil;
/**
* Servlet implementation class SearchServlet
*/
@WebServlet("/search")
public class SearchServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决中文乱码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
String sql = "select * from admin";
String sqlcount = "select count(*) from admin";
String[] colums = {"id","account","password"};
String data = MysqlUtil.getJsonBySql(sqlcount, sql, colums);
System.out.println(data);
response.getWriter().write(data);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
DeleteServlet.java代码:
package com.qcby.servlet;
import java.io.IOException;
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.qcby.db.MysqlUtil;
/**
* Servlet implementation class DeleteServlet
*/
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决中文乱码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
String id = request.getParameter("id");
System.out.println(id);
String sql = "delete from admin where id="+id;
int res = MysqlUtil.del(sql);
String json = "";
if (res==0) {
json = "{"code":"2020","message":"删除失败"}";
}else {
json = "{"code":"2020","message":"删除成功"}";
}
response.getWriter().append(json);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
InsertServlet.java代码:
package com.qcby.servlet;
import java.io.IOException;
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.qcby.db.MysqlUtil;
/**
* Servlet implementation class InsertServlet
*/
@WebServlet("/InsertServlet")
public class InsertServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public InsertServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决中文乱码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
String account = request.getParameter("account");
String password = request.getParameter("password");
System.out.println(account+" "+password);
String sql = "insert into admin(account,password) values('"+account+"','"+password+"');";
int res = MysqlUtil.add(sql);
String json = "";
if (res==0) {
json = "{"code":"2020","message":"注册失败"}";
}else {
json = "{"code":"2020","message":"注册成功"}";
}
response.getWriter().append(json);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
UpdateServlet.java代码:
package com.qcby.servlet;
import java.io.IOException;
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.qcby.db.MysqlUtil;
/**
* Servlet implementation class UpdateServlet
*/
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpdateServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决中文乱码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/json;charset=utf-8");
String id = request.getParameter("id");
String account = request.getParameter("account");
String password = request.getParameter("password");
System.out.println(id+" "+account+" "+password);
String sql = "update admin set account = '"+account+"',password = '"+password+"' where id = "+id;
int res = MysqlUtil.update(sql);
String json = "";
if (res==0) {
json = "{"code":"2020","message":"修改失败"}";
}else {
json = "{"code":"2020","message":"修改成功"}";
}
response.getWriter().append(json);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
数据库部分
使用navicat创建,设置id,account,password三个数据,都设定不能为空,将id设为主键,自增
最后
以上就是疯狂书包为你收集整理的登录,注册,修改用户名密码,删除用户的实现(前端+后端+数据库)的全部内容,希望文章能够帮你解决登录,注册,修改用户名密码,删除用户的实现(前端+后端+数据库)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复