Detailed example of Go using Gin+mysql to implement addition, deletion, modification and query

Detailed example of Go using Gin+mysql to implement addition, deletion, modification and query

Catalogue 0. Prerequisite knowledge 1. Architecture 2. Function module 3. Implementation process 4. Code 5. Results Summary 0.Prerequisite knowledge struct in Go. mysql, Gin framework. Web basics. 1. Architecture Use mysql as the database and Gin as the web framework. 2. Function module 1. Customize Person structure 2. Implement addition, deletion, modification and query of Person. Query or query all based on id Insert Modify Delete 3. Implementation process 1. Establish a database connection pool db, and then connect to the specified database. 2. Write a Web interface (add, delete, modify and check) 3. Test through postman or direct web page request test. 4. Code package main //Import module import ( “bytes” “database/sql” “fmt” “github.com/gin-gonic/gin” _ “github.com/go-sql-driver/mysql” “log” “net/http” “strconv” ) var db *sql.DB // Person custom Person class type Person struct { Id int `json:”id”` FirstName string `json:”first_name” form:”first_name”` LastName string `json:”last_name” form:”last_name”` } func (p *Person) get(db *sql.DB) (person Person, err error) { row := db.QueryRow(“SELECT id,first_name,last_name from person where id=?”, p.Id) err = row.Scan(&person.Id, &person.FirstName, &person.LastName) if err != nil { return } return } func (p *Person) getAll(db *sql.DB) (persons []Person, err error) { rows, err := db.Query(“select id,first_name,last_name from person”) fmt.Println(rows) if err != nil…

Development notes: MongoDB addition, deletion, modification and query

Development notes: MongoDB addition, deletion, modification and query

Preface: This article is organized by the editor of Programming Notes#. It mainly introduces the knowledge related to addition, deletion, modification and query of MongoDB. I hope it will be of certain reference value to you. This article mainly introduces the addition, deletion, modification and query operations of MongoDB database. increase mongoDB, like other relational databases, adds data to Go to the collection. db.collectionName.insert(content) Show all collections in the database: show collections delete Delete a collection through remove in MongoDB documents that meet certain conditions. remove accepts one parameter. As a condition for finding the document to be deleted: Of course, you can also delete an entire collection directly through the drop method: db. person.drop() Deleting the collection and then re-indexing is faster than deleting all documents in the collection. Change The modification operation is more complicated than adding and deleting, because MongoDB Not only can you use the update method, you can also use a lot of auxiliary modifiers. Let’s talk about the update method first. update The update method accepts two parameters, the first is the qualification to find the document, the second A new document that needs to be modified: ({“name”:”liufang”},post) in the above update, name:liufang is…

Mongodb basics 1: database creation and deletion, collection creation and deletion, data addition, deletion, modification and query

Mongodb basics 1: database creation and deletion, collection creation and deletion, data addition, deletion, modification and query

mongodb Chinese website 1. Database usage ./mongod –dbpath DB_PATH starts the mongodb service, and then ./mongo starts the client; Clear screen: cls View a list of all databases: show dbs 2. Create database Use database and create database: > use joyitsai If you really want to create this database successfully, you must insert data. Data cannot be inserted directly into the database, data can only be inserted into collections. There is no need to create a collection specifically. You only need to write some syntax to insert data and the collection will be created. The system found that student is an unfamiliar collection name, so it automatically created the collection: > db.student.insert({‘name’: ‘xiaoming’}); Display all collections in the current database (called tables in mysql): > show collections; Delete the current database: > db.dropDatabase(); Delete the specified collection (table): db.COOLECTION_NAME.drop(), for example, delete the above student collection: > db.student.drop(); 3. Insert data: Insert data. With the insertion of data, the database is created successfully and the collection is also created successfully: db.collection name.insert({“name”:”zhangsan”}); 4. Data search Query all data in the userinfo collection: > db.userinfo.find(); /*Equivalent to select * from userinfo;*/ Query the field data after deduplication: > db.userinfo.distinct(‘name’); Filter out…

Example of how webpack4+express+mongodb+vue implements addition, deletion, modification and query

Example of how webpack4+express+mongodb+vue implements addition, deletion, modification and query

This article mainly introduces examples of how webpack4+express+mongodb+vue implements additions, deletions, modifications and queries. The introduction in the article is very detailed and has certain reference value. Interested friends must read it. ! What is go Go is the abbreviation of golang. Golang is a statically strongly typed, compiled and concurrent type developed by Google. A programming language with garbage collection function, its syntax is similar to C language, but it does not include functions such as enumeration, exception handling, inheritance, generics, assertions, virtual functions, etc. Before explaining, let’s take a look at the effect as follows: 1) The effect of the entire page is as follows: 2) New data effect As follows: 3) The successful addition is as follows: 4) The effect of editing data is as follows: 5) The successful editing effect is as follows: 6) The effect of deleting data is as follows: 7) The effect of successful deletion is as follows: 8) The query effect is as follows: As above The effect is the same as before. Let’s first look at the structure of our entire project as follows: ### The directory structure is as follows: demo1           # Project name |…

Use examples to analyze JavaspringbootMongodb addition, deletion, modification and query

This article mainly uses examples to analyze Java springboot Mongodb additions, deletions, modifications and queries. The content is clear and concise. Friends who are interested in this can learn about it. I believe it will be helpful to everyone after reading it. 1. Add dependencies org.springframework.boot spring-boot-starter-data-mongodb 2.1.6.RELEASE Complete pom.xm file 4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.7.RELEASE com.vue demo 0.0.1-SNAPSHOT demo Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime com.alibaba fastjson 1.2.49 com.alibaba druid 1.0.26 org.projectlombok lombok 1.16.20 com.baomidou mybatis-plus-boot-starter 2.2.0 io.springfox springfox-swagger2 2.8.0 io.springfox springfox-swagger-ui 2.8.0 org.springframework.boot spring-boot-starter-data-mongodb 2.1.6.RELEASE org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine org.springframework.boot spring-boot-maven-plugin 2. applicaiton.yml server: port: 8081 mybatis-plus: ​typeAliasesPackage: com.vue.demo.entity ​mapperLocations: classpath:mapper/*.xml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezOne=GMT%2B8 username: root password: yang156122 driver-class-name: com.mysql.jdbc.Driver # Use druid data source type: com.alibaba.druid.pool.DruidDataSource redis: #redis stand-alone configuration host: localhost port: 6379 #Select the sub-database of the redis database database: 5 #redis connection pool configuration jedis: pool: max-idle: 10 min-idle: 5 max-active: 100 max-wait: 3000 timeout: 6005 data: mongodb: uri: mongodb://localhost:27017/userArticle 3. Mongodb addition, deletion, modification and query package com.vue.demo.service.serviceimpl; import com.alibaba.fastjson.JSONObject; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.vue.demo.entity.UserArticle; import com.vue.demo.service.UserArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import java.util.List; /** * @author yangwj *…

Detailed explanation of Django’s restful usage (built-in addition, deletion, modification and query)

What is rest REST is an architectural design guideline that all web applications should abide by. Representational State Transfer, translated as “presentation layer state transformation”. Resource-oriented is the most obvious feature of REST, a set of different operations for the same resource. A resource is a nameable abstract concept on the server. Resources are organized with nouns as the core. The first thing to focus on is the nouns. REST requires that various operations on resources must be performed through a unified interface. Only a limited set of operations can be performed on each resource. GET is used to obtain resources, POST is used to create new resources (can also be used to update resources), PUT (PATCH) is used to update resources, and DELETE is used to delete resources. api definition specification http://xxx.com/api/ Resources In the RESTful architecture, each URL represents a resource, so the URL cannot have verbs, only nouns, and the nouns used often correspond to the table names of the database. Generally speaking, the tables in the database are “collections” of the same type of records, so the nouns in the API should also be pluralized. For example, if there is an API that provides zoo information,…

mongoDB addition, deletion, modification and query

– This operation is done in the dos window Enter mongo to connect to the database show dbs can see which databases are on the current computer use Switch to a certain database //Switch to itying database//If not, switch to this database first, then add a piece of data, and then you can check it through show dbs This databaseuse itying Add data db.set.insert({key:value,key2:value2}) //In user Insert a piece of data like {“username”:”Zhang San”,”age”:20} into the tabledb.user.insert({“username”:”Zhang San”,”age”:20}) show collections View the collections of the current database db.collection.find() View the data of a certain collection //View the data in the user collection //There are no parameters in find here, and all data in the table will be displayeddb.user.find()//View the data with a attribute in the user collection, and the value of a attribute is 1 db.user.find( { a : 1 } ) db.dropDatabase() Delete the current database //Delete the database//Switch to this database first user itying//Then deletedb.dropDatabase() db.collection.drop() Delete a certain collection in the current database // Delete the user collection under the current databasedb.user.drop() –

MongoDB study notes (2) addition, deletion, modification and query

Query records General query > var cursor = db.things.find(); > while (cursor.hasNext()) printjson(cursor.next()); The above example shows cursor-style iteration output. The hasNext() function tells us whether there is still data, and if so, the next() function can be called. When we are using Javascript shell, we can use the features of JS, forEach can output the cursor. The following example uses forEach() Loop output: forEach() must define a function to be called for each cursor element. > db.things.find().forEach(printjson); In the MongoDB shell, we can also use cursors as arrays: > var cursor = db.things.find(); > printjson(cursor[4]); When using cursors, please pay attention to the problem of memory usage, especially for large cursor objects, which may cause memory failure. This use Output in an iterative way. The following example converts the cursor into a real array type: > var arr = db.things.find().toArray(); > arr[5];Conditional query > db.things.find({name:”mongo”}).forEach(printjson); > db.things.find({x:4,y:”abc”}).forEach(printjson); Return specific elements > db.things.find({x:4}, {j:true}).forEach(printjson); findOne() syntax printjson(db.things.findOne({name:”mongo”})); Limit the number of result sets through limit > db.things.find ().limit(3); Modify record > db.things.update({name:”mongo”},{$set:{name:”mongo_new”}}); Delete record > db.things.remove({name:”mongo_new”}); ​ ​

Insert picture description here

Django many-to-many table addition, deletion, modification and query

models.py from django.db import models class Role(models.Model):”””Role table”””role_name = models.CharField(max_length=32, unique=True) class Meta:db_table = “pp_role”class User(models.Model):”””User table”””username = models.CharField(max_length=32, verbose_name =”Name”)age &# 61; models.IntegerField(verbose_name= “Age”)home = models.CharField(verbose_name= “Hometown”, null=True, max_length=32)hight = models .IntegerField(verbose_name=”Height” , null=True )# many-to-manyroles = models .ManyToManyField(Role)class Meta:db_table &# 61; “pp_user” Manual table operation class ManyToManyTeest (APIView):def get(self, request):u_id = request.query_params.get('u_id' )r_id = request.query_params.get('r_id')if not all([u_id, r_id]):return Response({'code': 400, 'msg': 'Incomplete parameters'})# Query data from the models of manytomany under construction# user_obj = User.objects.get(id=u_id) # role_obj = user_obj.roles.all()# ser_obj = RoleSerializer(role_obj, many=True )# Reverse:Check data in models that have not established manytomanyrole_obj = Role.objects.get(id=r_id)user_obj = role_obj.user_set.all()ser_obj = UserSerializer(user_obj, many= True)return Response({'code': 200, 'data&#39 ;: ser_obj.data})def post (self, request):u_name = request.query_params.get('u_name')r_name = request.query_params.get('r_name')if not all([u_name, r_name]):return Response({'code': 400, 'msg' : 'Incomplete parameters'})# Adding data to the models under construction manytomany,(One item&#xff0c ;⼼An object)user_obj = User.objects.filter(username&# 61;u_name).first( )role_obj = Role.objects.filter(role_name =r_name).first( span>)# user_obj.roles.add(role_obj)# Reverse Add data,(one item,one object)user_obj = User.objects.filter(username=u_name)role_obj = Role.objects.filter(role_name=r_name).first()role_obj.user_set.add( *user_obj)return Response({'code': 200, 'data': 'Added successfully'})def put( self, request):u_id = request.query_params.get('u_id')r_id = request.query_params.get('r_id')if not all( [u_id, r_id]):return Response({'code': 400, 'msg': 'Incomplete parameters'})# Forwardly modify the data in the models building manytomany,The parameters can only be iterable objects# user_obj = User.objects.filter(id=u_id).first()# role_obj &#61 ; Role.objects.filter(id=r_id)# user_obj.roles.set(role_obj)# Inverse To…

Jmeter (7) Mongodb addition, deletion, modification and query

Jmeter (7) Mongodb addition, deletion, modification and query

1. Start JMeter, create a new thread group, and set the thread group properties 2. Right-click to add-MongoDB Source Config Set attribute Server Address List: 192.168.0.99 MongoDB Source: jmeterdbsource, set as shown below: 3. Right-click to add-Sampler-MongoDB Script Set the attribute MongoDB Source: refer to the good name set in the MongoDB source config, jmeterdbsource Database Name: database name, user MongoDB Script:Script 4. View the running results Before running: After running: The running server log is as follows:

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索