Python 65th days -- python mysql operations, 65th days -- python
The pymysql module performs
1 import pymysql 2 3 4 5 # create connection 6 conn = pymysql. connect (host = '2017. 0.0.1 ', port = 3306, user = 'root', passwd = 'root', db = 'test') 7 # create cursor 8 cursor = conn. cursor () 9 # create a table 10 using t_row = cursor.exe cute ("create table user (id int unsigned primary key auto_increment, name varchar (15) not NULL, age int (3) not NULL, addr varchar (255) default character set utf8; ") # create a table 11 12 13 # Execute SQL, and return the number of affected rows 14 # effect_row = cursor.exe cute ("update hosts set host = '1. 1.1.2 'where nid> % s ", (1,) 15 16 17 18 # Execute SQL, and return the number of affected rows executetables. The default transaction 19 cursor.exe cutetables ("insert into user (name, age, addr) values (% s, % s, % s )", [('XX', 35, 'ddd ')]) 20 # fig ("insert into user (name, age, addr) values (% s, % s, % s) ", data) 21 # conn. commit () # Close transaction 22 23 24 # commit, otherwise the newly created or modified data cannot be saved 25 conn. commit () 26 27 # Close cursor 28 cursor. close () 29 # close connection 30 conn. close ()View Code
Sqlalchemy Module
1 from sqlalchemy. ext. declarative import declarative_base 2 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index 3 from sqlalchemy. orm import sessionmaker, relationship 4 from sqlalchemy import create_engine 5 # User Password host library 6 engine = create_engine ("mysql + pymysql: // root: root@127.0.0.1: 3306/test ", encoding = "UTF-8", echo = True) 7 8 Base = declarative_base () # generate an orm Base class 9 class User (Base ): 10 _ tablename __= 'info _ L' # table name 11 id = Column (Integer, primary_key = True) # Set the integer type to primary key 12 name = Column (String (32) # String type 13 addrs = Column (String (256) 14 15 Base. metadata. create_all (engine) # Create Table 16 17 Session_class = sessionmaker (bind = engine) # create a Session class with the database 18 Session = Session_class () # generate instance 19 20 user_obj = User (name = "sdf", addrs = "sdfs") # generate the data object you want to create 21 print (user_obj.name, user_obj.addrs) # At this time, no object 22 Session is created. add (user_obj) # enable transaction connection 23 Session. commit () # Close a transaction
Remarks install related modules
Install the mysqldb Module
Centos7: Installation
Yum install MYSQL-python # install mysqldb automatically without python3yum install pymysql # install the pymysql framework
Windows: Under cmd
pip3 install pymysql