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

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

一、效果展示

添加并显示

在这里插入图片描述
更新并显示

在这里插入图片描述
删除同理,就不放图了---------

二、相关知识点

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

参数:
在这里插入图片描述

官方示例代码:

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

参数:
在这里插入图片描述

官方示例代码:

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);
    }
}
数据库的相关设计如下

在这里插入图片描述

  • 16
    点赞
  • 158
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
### 回答1: 微信小程序连接 MySQL 实现增删改查需要使用一个后端语言来操作数据库。具体来说,需要在小程序前端使用 JavaScript 发送请求,在后端使用 Node.js 来接收请求并与 MySQL 交互。 首先,你需要在小程序前端使用 wx.request 发送请求,这个请求会被 Node.js 服务器接收到。在小程序中请求可以这样写: ``` wx.request({ url: 'https://example.com/insert', // 服务器地址 method: 'POST', data: { name: 'John Doe', age: 30 }, success (res) { console.log(res.data) } }) ``` 其次,在服务器端使用 Node.js 使用 `mysql`库 来连接和操作数据库 ``` const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'password', database: 'test' }); connection.connect(); app.post('/insert', (req, res) => { const { name, age } = req.body; const sql = `INSERT INTO users (name, age) VALUES ('${name}', ${age})`; connection.query(sql, (error, results) => { if (error) throw error; res.send(results); }); }); ``` 在这里是 增加的例子, 删除,修改,查询操作语句类似。 需要注意的是,将数据库的相关信息(用户名、密码等)和 SQL 语句放在前端是不安全的,应该放在后端进行处理。 上面给出的代码只是一个示例,实际开发中还 ### 回答2: 微信小程序是一种基于微信平台的应用程序,它具有轻便、快速、跨平台的特点。连接MySQL数据库实现小程序数据存储和管理的一种常见方式。下面是一个简要的步骤,用于在微信小程序中连接MySQL数据库实现增删改查操作。 1. 首先,在小程序项目的后端服务器上安装并配置MySQL数据库服务。确保数据库服务正常运行,并创建相关的数据表存储需要的数据。 2. 在小程序的后端服务器代码中,使用适当的方式(如Node.js)连接MySQL数据库。这可以通过安装MySQL模块以及配置数据库连接信息来实现。 3. 创建一个与MySQL数据库交互的API,用于处理小程序与数据库之间的数据传输。可以使用HTTP请求(如POST和GET)将数据发送到服务器和接收服务器返回的数据。 4. 编写小程序前端代码,实现用户界面和交互逻辑。通过调用后端服务器的API,向MySQL数据库发送请求,并将结果显示给用户。 5. 实现增删改查功能,可以通过发送包含相关参数的API请求,来向数据库添加新的数据、更新已有数据或删除数据。同时,可以通过发送查询请求,从数据库中检索需要的数据。 6. 在小程序前端界面上显示来自数据库的数据。根据需求,可以使用列表、表格、图表等方式展示数据,并提供相应的操作按钮或选项。 需要注意的是,为了保证数据安全和防止恶意攻击,需要对数据库连接和API请求进行安全性处理,如输入合法性验证、防范SQL注入等。此外,为提高数据操作效率,可以考虑使用数据库索引、合理优化查询语句等方法。 总结起来,实现微信小程序连接MySQL数据库增删改查操作,需要在服务器端配置MySQL数据库服务并编写相应的API,同时在小程序前端代码中调用这些API实现数据的传输和展示。 ### 回答3: 微信小程序MySQL数据库的连接可以通过服务端进行实现。下面是一个简单的示例,演示如何在微信小程序中连接MySQL数据库并进行增删改查操作。 1. 首先,需要在服务端搭建一个用于连接MySQL数据库的接口,可以使用Node.js与Express框架来实现。在接口中,需要引入MySQL模块,配置数据库连接信息,并编写相应的SQL语句来执行增删改查操作。 2. 在微信小程序的前端代码中,可以通过wx.request方法来发送HTTP请求,与服务端接口进行数据交互。可以在小程序的某个页面中编写表单,输入要进行的操作以及相应的数据,当点击提交按钮时,使用wx.request方法发送请求到服务端接口。 3. 在服务端接口中,根据前端发送的请求,解析相应的参数,执行对应的SQL语句进行增删改查操作。将操作结果返回给前端。 4. 在微信小程序的前端代码中,接收服务端返回的数据,并根据需要进行相应的处理和展示。 需要注意的是,连接MySQL数据库的接口需要进行安全验证,防止恶意操作和信息泄露。同时,需要注意及时对用户输入的数据进行参数校验和过滤,防止SQL注入等安全风险。 以上是一个简单的描述,实际实现过程中还需要根据具体的需求进行详细设计和编码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋千水竹马道

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值