Docker (7): Connect to a database using Python, insert and query data--link

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/53589604 not allowed to reprint without the Bo master.
Bo main address is: Http://blog.csdn.net/freewebsys

1, connect two Docker

First, you need to build the environment:
Create the MARIADB database below Alpine:
http://blog.csdn.net/freewebsys/article/details/53540615
User name password is root.
Then create the HTTP Python environment:
http://blog.csdn.net/freewebsys/article/details/53509676
Next, do a simple data query and insert operation.

2,python Code:

main.py

#!/usr/bin/python#-*-Coding:utf-8-*- fromFlaskImportFlaskImportMysqldbapp = Flask (__name__) Mysql_host ="MySQL"Mysql_user ="Root"Mysql_pwd ="Root"Mysql_db_name ="Demo""" " CREATE DATABASE ' demo ' DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci; CREATE TABLE ' demo '. ' User_info ' (' id ' bigint) not NULL auto_increment, ' name ' varchar ($) DEFAULT null,primary KEY (' ID ') Engine=innodb DEFAULT Charset=utf8; "" def query_db(SQL):db = MySQLdb.connect (Mysql_host, Mysql_user, mysql_pwd, mysql_db_name) cur = db.cursor ()Try: Cur.execute (sql) result = Cur.fetchall ()except: Print ("Error:sql:"+ sql) Cur.close () Db.close ()returnResult def update_db(SQL):print (SQL) db = MySQLdb.connect (Mysql_host, Mysql_user, mysql_pwd, mysql_db_name) cur = db.cursor ()Try: Cur.execute (SQL)except: Print ("Error:sql:"+ sql) Db.commit () Cur.close () Db.close ()@app. Route ("/list") def list():Results = query_db ("Select Id,name from ' demo '. ' User_info '") out ="results:\n"     forResultinchResults:id = result[0] name = result[1] Out + ="ID:"+ str (ID) +", Name:"+ name +"\ n"    returnOut@app. Route ("/add") def add():sql ="Insert ignore into ' demo '. ' User_info ' (' name ') VALUES (' Zhangsan ')"update_db (SQL)return "OK"if__name__ = ="__main__": App.run (host=' 0.0.0.0 ', port= the)

The code is not much different from the previous HTTP, but it only adds query and insert operations to the database.
Altogether there are two URLs, a list, query all data, an add, write dead increase.

3. Create a database table

MySQL needs to create the following database and table:

 CREATE DATABASE ' demo ' DEFAULT CHARACTER SET UTF8  COLLATE utf8_general_ci; CREATE TABLE ' demo '. ' User_info ' (' id ' bigint () not  NULL auto_increment,' name ' varchar( () DEFAULT NULL,PRIMARY KEY (' id ')) engine= InnoDB DEFAULT Charset=utf8;

This User_info table has a total of two fields, an ID increment, and a name string.
Of course, this database is not local and is another Docker container.
HTTP is above a container.

4, use link to link up

The data creation name is called MARIADB.
Run HTTP.

-d-p5000:5000--name py-http--link mariadb:mysql demo/py-http:1.0

Pay special attention to the –link container name: Nickname, and then for the Py-http container, MySQL is the nickname.
You can look directly at the EVN environment:

# docker exec-it py-http bashbash-4.3# envHOSTNAME=db7f7aba7c2fMysql_env_mysql_root_password=rootmysql_env_mariadb_version=10.1.19+maria-1~jessiemysql_env_gosu_version=1.7Mysql_port_3306_tcp_port=3306Mysql_env_mariadb_major=10.1mysql_port_3306_tcp=tcp://172.17.0.2:3306PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/binPWD=/TZ=asia/shanghaiSHLVL=1HOME=/rootMysql_name=/py-http/mysqlMysql_port_3306_tcp_proto=tcpmysql_port_3306_tcp_addr=172.17.0.2Mysql_port=tcp://172.17.0.2:3306_=/usr/bin/env

As you can see, the environment variables of the MARIADB container have been introduced directly under the Py-http container.
and view hosts:

# cat/etc/hosts  127.0  .0  .1  Localhost::1  localhost ip6-localhost ip6-loopbackfe00:< /span>:0  ip6-localnetFF00: : 0  ip6-mcastprefixFF02: : 1  ip6-allnodesff02: : 2  Ip6-allrouters172.17  .0  .2  mysql 48  bd5fbf3ddc mariadb172.17  .0  .3  db7f7aba7c2f 

You can see the host with the MySQL variable.
External access: Indicates that the test was successful. The database can be inserted into the query.

# curl http://127.0.0.1:5000/addok[root@localhost http]# curl http://127.0.0.1:5000/listresults:id:1,name:zhangsanid:2,name:zhangsan

4, summary

The text of this text connection is: http://blog.csdn.net/freewebsys/article/details/53589604 not allowed to reprint without the Bo master.
Bo main address is: Http://blog.csdn.net/freewebsys

Docker design is good, each container is independent, but can also be connected together.
This makes up a micro-service cluster. Separate the code from the environment with environment variables.
Ensure the consistency of test environment, development environment and online environment.
Greatly facilitates the development of operations, the link command is also very good.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.