微信小程序+mysql实现增删改查

目录

    • 微信小程序+mysql实现增删改查
      • 一、效果展示
      • 二、相关知识点
        • 1、wx.chooseImage(Object object) 选择图片
        • 2、wx.uploadFile(Object object) 上传文件
        • 3、wx.request(Object object) 发起HTTPS网络请求
        • 4、微信小程序--input输入值的获取和传递
        • 5、两个页面之间传值
          • 1.url传值
          • 2.本地存储
          • 3.全局的app对象
        • 6、data-绑定数据
      • 三、源码
        • add.wxml
        • add.wxss
        • add.js
        • list.wxml
        • list.wxss
        • list.js
        • update.wxml
        • update.wxss
        • update.js
        • FileUpload.java
        • FileDao.java
        • UpdateDevice.java
        • DeleteDevice.java
        • 数据库的相关设计如下

微信小程序+mysql实现增删改查

一、效果展示

添加并显示

微信小程序+mysql实现增删改查_第1张图片
更新并显示

微信小程序+mysql实现增删改查_第2张图片
删除同理,就不放图了---------

二、相关知识点

1、wx.chooseImage(Object object) 选择图片

参数:
微信小程序+mysql实现增删改查_第3张图片

官方示例代码:

wx.chooseImage({
  count: 1,
  sizeType: ['original', 'compressed'],
  sourceType: ['album', 'camera'],
  success (res) {
    // tempFilePath可以作为img标签的src属性显示图片
    const tempFilePaths = res.tempFilePaths
  }
})

2、wx.uploadFile(Object object) 上传文件

参数:
微信小程序+mysql实现增删改查_第4张图片

官方示例代码:

wx.chooseImage({
  success (res) {
    const tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'https://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData: {
        'user': 'test'
      },
      success (res){
        const data = res.data
        //do something
      }
    })
  }
})

3、wx.request(Object object) 发起HTTPS网络请求

官方说明文档

  1. 参数很多,这里介绍几个常用的
  • url: 服务器的url地址
  • data: 请求的参数可以采用String data:"xxx=xxx&xxx=xxx"的形式或者Object data:{“userId”:1}的形式
  • method: http的方法,默认为GET请求
  • header: 设置请求的header
  • success: 接口成功的回调
  • fail: 接口失败的回调
  • complete: 调用接口结束之后的回调,无论成功或者失败该接口都会被调用
  1. data 参数说明
    最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
  • 对于 GET 方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)
  • 对于 POST 方法且 header[‘content-type’] 为 application/json 的数据,会对数据进行 JSON 序列化
  • 对于 POST 方法且 header[‘content-type’] 为 application/x-www-form-urlencoded 的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)
  1. 示例代码:
wx.request({
  url: 'example.php', //仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)//res.data 开发者服务器返回的数据
  }
})

4、微信小程序–input输入值的获取和传递

  1. wxml 为input绑定一个bindinput事件
 <input class="input" placeholder="请输入设备id" bindinput="deviceIdInput" placeholder-class="placeholder-style">input>
  1. js 在js中定义一个变量
data: {
    device_id:''
  },
  1. js 在js中用刚刚绑定的事件为其赋值
  deviceIdInput:function(e){
    this.setData({
      device_id:e.detail.value
    });
  

5、两个页面之间传值

1.url传值

A页面

wx.navigateTo({
  url: 'test?id=1'
})

B页面

Page({
  data:{
    id:'',
  },
  onLoad: function(option){
    this.setData({
      id:option.id
    })
  }
})
2.本地存储

A页面

wx.setStorageSync('username', 'ddd')

B页面

Page({
  data:{
    username:'',
  },
  onLoad: function(){
   var username = wx.getStorageSync('username')
   this.setData({
       username: username
    })
  }
})
3.全局的app对象

A页面

var app = getApp();
app.username='ddd';

B页面

var app = getApp();
var username = app.username;

6、data-绑定数据

<view bindtap="SetData" data-name="xxx" data-age="{{age}}">
  获取数据
view>

js

Page({
  data:{
    name:'',
    age:0
  },
  SetData:function(e){
    console.log(e);
    this.setData({
      name:e.target.dataset.name 
      age:e.currentTarget.dataset.item
    });
    console.log(this.data.name);
  }
})

三、源码

add.wxml

<form bindsubmit="formSubmit" class="input-wrapper">
    <view class="title">设备提交表单view>
  <view class="input-data">
    <input class="input" placeholder="请输入设备id" bindinput="deviceIdInput" placeholder-class="placeholder-style">input>
     <view class="underline">view>
  view>
  <view class="input-data">
    <input class="input" placeholder="请输入设备名称" bindinput="deviceNameInput" placeholder-class="placeholder-style">input>
    <view class="underline">view>
  view>
  <view class="input-data">
    <input class="input" placeholder="请输入设备创建日期" bindinput="deviceDateInput" placeholder-class="placeholder-style">input>
    <view class="underline">view>
  view>
  <view class="input-data">
    <input class="input" placeholder="请输入设备数量" bindinput="deviceNumberInput" placeholder-class="placeholder-style">input>
    <view class="underline">view>
  view>
  <view class="input-upload"> 
    <button bindtap="uploadimg" style="width:80vw;height:12vw;font-size: 48rpx;color: #a18b8b;margin-bottom: 30rpx;">选择上传的设备图button>
  view>
  <view class="input-submit" > 
    <button form-type='submit' style="width:80vw;height:12vw;font-size: 48rpx;color: #a18b8b;margin-bottom: 30rpx;">提交button>
  view>
form>  
<image class="device_image" src="{{source}}" style="width:100px;height:100px ">image>

add.wxss

body {
  display: flex;
  justify-content: center;
  align-items: center;
  /* min-height: 100vh; */
  padding: 0;
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
  outline: none;
}
.input-wrapper {
  width: 450px;
  background-color: rgb(255, 255, 255);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.title{
  text-align: center;
  color: #a18b8b;
  font-size: 24px;
  text-transform: uppercase;
}
.input-data {
  position: relative;
  margin-left: 70rpx;
  width: 80%;
  height: 40px;
  margin-top: 20px;
}
.input-data input {
  width: 100%;
  height: 100%;
  border: none;
  border-bottom: 2px solid silver;
  font-size: 17px;
  color: #a18b8b;
}
.input-data .underline {
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 2px;
  transition: all 0.3s ease;
  transform: scale(0);
}

.input-wrapper .input-upload {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  height: 80px;
}

.input-wrapper .input-submit {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  height: 60px;
}

.input-wrapper .input-submit input {
  padding: 10px 20px;
  border-radius: 50px;
  border: none;
  color: white;
  background: linear-gradient(-135deg, #c850c0, #4158d0);
}
.device_image{
  margin-left: 200rpx;
}


.placeholder-style {
  color: #a18b8b;
}

add.js

Page({
  /**
   * 页面的初始数据
   */
  data: {
  //初始化为空
    source:' ', //临时存储图片路径
    file_url:'', //对应数据库中的虚拟路径
    file_path:'', //对应数据库中的本地图片存在目录
    size:'', //对应数据库中图片大小
    device_id:'',//对应数据库中设备id
    device_name:'',//对应数据库中设备名
    device_number:'',//数据库中设备数量
    device_date:'',//数据库中设备创建日期
  },
/**
 * 上传图片
 */
  uploadimg:function(){
    var that = this;
    wx.chooseImage({  //从本地相册选择图片或使用相机拍照
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success:function(res){
        //console.log(res)
       //前台显示
        that.setData({
          source: res.tempFilePaths
        })
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
         wx.uploadFile({
          url: 'http://localhost:8080/FileUpLoad',
          filePath: tempFilePaths[0],
          name: 'file',
          success:function(res){
            //打印
            console.log(res.data)
            var data=JSON.parse(res.data);
            that.setData({
              file_url:data.file_url, 
              file_path:data.file_path,
              size:data.size
            })
          }
        })
      }
    })
  },
  //提交表单
  formSubmit:function(){
    let that=this;
    wx.request({
      url: 'http://localhost:8080/FileDao',
      method:"POST",
      data:{
        device_id:that.data.device_id,
        device_name:that.data.device_name,
        device_number:that.data.device_number,
        device_date:that.data.device_date,
        file_url:that.data.file_url,
        file_path:that.data.file_path,
        size:that.data.size
      },
      header:{
        "Content-type":"application/x-www-form-urlencoded"
      },
      success:function(res){
        console.log(res.data);
        wx.navigateTo({
          url: '../list/list'
        })
        wx.showToast({
          title: '提交成功',
        })
      }
    })
  },
  deviceIdInput:function(e){
    this.setData({
      device_id:e.detail.value
    });
  },
  deviceNumberInput:function(e){
    this.setData({
      device_number:e.detail.value
    });
  },
  deviceNameInput:function(e){
    this.setData({
      device_name:e.detail.value
    });
  },
  deviceDateInput:function(e){
    this.setData({
      device_date:e.detail.value
    });
  },
})

list.wxml

<view class="add_button">
  <button  style="width:80vw;height:10vw;font-size: 30rpx;color: #a18b8b;margin-bottom: 30rpx;" bindtap="add_device">添加设备button>
view>
<view class="items" wx:for="{{list}}" >  
   <view class="device_list">
        <view class="device_container">
           <image class="device_image" src="{{item.file_url}}">image> 
           <view class="device_text">
               <view class="text">设备id:{{item.device_id}}view>
               <view class="text">设备名称:{{item.device_name}}view>  
               <view class="text">设备数量:{{item.device_number}}view>  
               <view class="text">创建时间:{{item.device_date}}view>  
           view>
           <view >
            <button style="width:30vw;height:10vw;font-size: 30rpx;color: #a18b8b;margin-bottom: 15rpx;" class="caozuo" bindtap="update_device" data-item="{{item}}">修改button>
            <button style="width:30vw;height:10vw;font-size: 30rpx;color: #a18b8b;" class="caozuo" bindtap="delete_device" data-id="{{item.id}}">删除button>
        view>
          view>
   view>
view>

list.wxss

.add_button{
  border-bottom: 1rpx solid #eee;
}
.items{
  display: flex;
  flex: 1;
  flex-direction: column;
}
.device_container{
  display: flex;
  padding: 20rpx 40rpx;
  border-bottom: 1rpx solid #eee;
  cursor: pointer;
}
.device_image{
  width: 128rpx;
  height: 128rpx;
  margin-right: 20rpx;
}
.device_text{
  flex: 1;
  
}
.text{
  font-size: 22rpx;
  color: #a18b8b;
  display: block;
  margin-bottom: 15rpx;
}

list.js

// pages/list/list.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list:[],
    id:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
onLoad(option){
  var that=this;
 wx.request({
            url: 'http://localhost:8080/device_file_servlet_action?action=get_device_record',
            success:function(res){
              console.log(res.data.aaData);
              that.setData({
                list: res.data.aaData,//将表中查询出来的信息传给list
                })
              wx.showToast({
                title: '刷新成功',
              })
            },
            fail: ()=>{},
            complete: ()=>{}
       });
},
delete_device:function(e){
  this.setData({
    id:e.currentTarget.dataset.id
  })
  let that=this;
  wx.request({
    url: 'http://localhost:8080/DeleteDevice',
    data:{
      id:that.data.id
    },
    success:function(res){
      wx.navigateTo({
        url: '../list/list'
      })
      wx.showToast({
        title: '删除成功',
      })
    },
    fail: ()=>{},
    complete: ()=>{}
});
},
update_device:function(e){
  wx.setStorageSync('item',e.currentTarget.dataset.item)
  wx.navigateTo({
    url: '../update/update',
  })
},
add_device:function(){
  wx.navigateTo({
    url: '../add/add'
  })
}
})

update.wxml

<form bindsubmit="formSubmit" class="input-wrapper">
    <view class="title">设备提交表单view>
  <view class="input-data">
    <input class="input" placeholder="请输入设备id" bindinput="deviceIdInput" value="{{device_id}}" placeholder-class="placeholder-style">input>
     <view class="underline">view>
  view>
  <view class="input-data">
    <input class="input" placeholder="请输入设备名称" bindinput="deviceNameInput" value="{{device_name}}" placeholder-class="placeholder-style">input>
    <view class="underline">view>
  view>
  <view class="input-data">
    <input class="input" placeholder="请输入设备创建日期" bindinput="deviceDateInput" value="{{device_date}}" placeholder-class="placeholder-style">input>
    <view class="underline">view>
  view>
  <view class="input-data">
    <input class="input"  placeholder="请输入设备数量" bindinput="deviceNumberInput" value="{{device_number}}"  placeholder-class="placeholder-style">input>
    <view class="underline">view>
  view>
  
  <view class="input-upload"> 
    <button bindtap="uploadimg" style="width:80vw;height:12vw;font-size: 48rpx;color: #a18b8b;margin-bottom: 30rpx;">选择上传的设备图button>
  view>
  <view class="input-submit" > 
    <button form-type='submit' style="width:80vw;height:12vw;font-size: 48rpx;color: #a18b8b;margin-bottom: 30rpx;">提交button>
  view>
form>  
<image class="device_image" src="{{source}}" style="width:100px;height:100px ">image>

update.wxss

与add.wxss一样,这里就不放源码了

update.js

与add.js其他部分一样,只增加了一部分给表单初始化数据的部分,这里用的是本地缓存的方式,更新的时候需要多传入一个id值,根据id更新。

onLoad:function(options){
    var item=wx.getStorageSync('item');
    console.log(item.id)
    this.setData({
      // items:item
      device_id:item.device_id,
      device_name:item.device_name,
      device_date:item.device_date,
      device_number:item.device_number,
      file_url:item.file_url,
      file_path:item.file_path,
      id:item.id,
      size:item.size,
      source:item.file_url
    })
  },
    formSubmit:function(){
    let that=this;
    console.log(that.data.id+"=================")
    console.log(that.data.device_id)
    console.log(that.data.device_name)

    wx.request({
      url: 'http://localhost:8080/UpdateDevice',
      method:"POST",
      data:{
        id:that.data.id,
        device_id:that.data.device_id,
        device_name:that.data.device_name,
        device_number:that.data.device_number,
        device_date:that.data.device_date,
        file_url:that.data.file_url,
        file_path:that.data.file_path,
        size:that.data.size
      },
      header:{
        "Content-type":"application/x-www-form-urlencoded"
      },
      success:function(res){
        console.log(res.data);
        wx.navigateTo({
          url: '../list/list'
        })
        wx.showToast({
          title: '提交成功',
        })
      }
    })
  },

FileUpload.java

上传文件

public class FileUpLoad extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("===================================dopost开始了");
        request.setCharacterEncoding("utf-8");	//设置编码
        //获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //获取文件需要上传到的路径
        String path = "E:/upload";
        //如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
        //设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
        /*
         * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,
         * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
         * 然后再将其真正写到 对应目录的硬盘上
         */
        factory.setRepository(new File(path));
        //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
        factory.setSizeThreshold(1024*1024) ;
        //高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            //可以上传多个文件
            List<FileItem> list = (List<FileItem>)upload.parseRequest(request);
            for(FileItem item : list)
            {
                //获取表单的属性名字
                String name = item.getFieldName();
                //如果获取的 表单信息是普通的 文本 信息
                if(item.isFormField())
                {
                    //获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的
                    String value = item.getString() ;
                    request.setAttribute(name, value);
                }
                //对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
                else
                {
                    //获取路径名
                    String value = item.getName() ;
                    //索引到最后一个反斜杠
                    int start = value.lastIndexOf("\\");
                    //截取 上传文件的 字符串名字,加1是 去掉反斜杠,
                    String filename = value.substring(start+1);
                    System.out.println(filename);
                    request.setAttribute(name, filename);
                    //真正写到磁盘上
                    //它抛出的异常 用exception 捕捉
                    //item.write( new File(path,filename) );//第三方提供的
                    //手动写的
                    OutputStream out = new FileOutputStream(new File(path,filename));
                    InputStream in = item.getInputStream() ;
                    // HttpSession session =request.getSession(); 
                    // session.setAttribute("url","/upload/"+filename);
                    // session.setAttribute("file_path","E:/upload");
                    int length = 0 ;
                    byte [] buf = new byte[1024] ;
                    System.out.printf("获取上传文件的总共的容量:%s%n", item.getSize());
                    String size= String.valueOf(item.getSize());
                    // session.setAttribute("size",size+"K");
                    // in.read(buf) 每次读到的数据存放在   buf 数组中
                    while( (length = in.read(buf) ) != -1)
                    {
                        //在   buf 数组中 取出数据 写到 (输出流)磁盘上
                        out.write(buf, 0, length);
                    }

                    in.close();
                    out.close();

                    //返回结果
                    JSONObject json=new JSONObject();
                    String objectId="OBJECT_"+(new SimpleDateFormat("yyyyMMddHHmmss")).format(new java.util.Date());
                    String file_url="http://localhost:8080/upload/"+filename;
                    json.put("objectId",objectId);
                    json.put("file_url",file_url);
                    json.put("file_path",path);
                    json.put("size",size+"K");
                    response.getWriter().print(json);
                    response.getWriter().flush();
                    response.getWriter().close();

                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

//        response.sendRedirect(request.getContextPath()+"/front.jsp");
    }

}

FileDao.java

对数据库进行插入操作

public class FileDao extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String deviceId=req.getParameter("device_id");
        String deviceName=req.getParameter("device_name");
        String deviceNumber=req.getParameter("device_number");
        String deviceDate=req.getParameter("device_date");
        String FilePath=req.getParameter("file_path");
        String FileUrl=req.getParameter("file_url");
        String size=req.getParameter("size");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); //低版本改成 Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException classnotfoundexception) {
            classnotfoundexception.printStackTrace();
        }
        // 然后链接数据库,开始操作数据表
        try {

            String connStr="jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&user=xxx&password=xxxx";
            Connection connection = DriverManager.getConnection(connStr);
            System.out.println("准备statement。connection是:"+connStr);
            Statement statement = connection.createStatement();
            System.out.println("已经链接上数据库!");
            String sql="insert into xxx(device_id,device_name,device_number,device_date,file_path,size,file_url)";
            sql=sql+" values('"+deviceId+"'";
            sql=sql+", '"+deviceName+"'";
            sql=sql+", '"+deviceNumber+"'";
            sql=sql+", '"+deviceDate+"'";
            sql=sql+", '"+FilePath+"'";
            sql=sql+", '"+size+"'";
            sql=sql+" ,'"+FileUrl+"')";
            statement.executeUpdate(sql);
            statement.close();
            connection.close();
        } catch (SQLException sqlexception) {
            sqlexception.printStackTrace();
        }
    }
}

UpdateDevice.java

对数据库进行更新

public class UpdateDevice extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        String id=req.getParameter("id");
        String deviceId=req.getParameter("device_id");
        String deviceName=req.getParameter("device_name");
        String deviceNumber=req.getParameter("device_number");
        String deviceDate=req.getParameter("device_date");
        String FilePath=req.getParameter("file_path");
        String FileUrl=req.getParameter("file_url");
        String size=req.getParameter("size");

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException classnotfoundexception) {
            classnotfoundexception.printStackTrace();
        }
        try {

            String connStr="jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&user=xxx&password=xxx";
            Connection connection = DriverManager.getConnection(connStr);
            System.out.println("准备statement。connection是:"+connStr);
            Statement statement = connection.createStatement();
            System.out.println("已经链接上数据库!");
            String sql="update xxx set ";
            sql=sql+"device_id="+"'"+deviceId+"'"+",";
            sql=sql+"device_name="+"'"+deviceName+"'"+",";
            sql=sql+"device_number="+"'"+deviceNumber+"'"+",";
            sql=sql+"device_date="+"'"+deviceDate+"'"+",";
            sql=sql+"file_path="+"'"+FilePath+"'"+",";
            sql=sql+"file_url="+"'"+FileUrl+"'"+",";
            sql=sql+"size="+"'"+size+"'"+" ";
            sql=sql+"where id="+id;
            System.out.println(sql);
            statement.executeUpdate(sql);
            statement.close();
            connection.close();
        } catch (SQLException sqlexception) {
            sqlexception.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

DeleteDevice.java

对数据库进行删除

public class DeleteDevice extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id =request.getParameter("id");
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException classnotfoundexception) {
            classnotfoundexception.printStackTrace();
        }
        try {
            String connStr = "jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&user=xxx&password=xxx";
            Connection connection = DriverManager.getConnection(connStr);
            System.out.println("准备statement。connection是:" + connStr);
            Statement statement = connection.createStatement();
            System.out.println("已经链接上数据库!");
            String sql = "delete from xxx where id=";
            sql += id;
            statement.executeUpdate(sql);
            statement.close();
            connection.close();
        } catch (SQLException sqlexception) {
            sqlexception.printStackTrace();
        }
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

数据库的相关设计如下

微信小程序+mysql实现增删改查_第5张图片

你可能感兴趣的:(微信小程序,微信小程序,数据库)