Python database

A: Database Basics:

Database: storing data warehouse 

sql and specification: SQL command set is designed for the operation of the database established, is a full-featured database languages

Log mysql: mysql -u username -p password
-mysql -h 127.0.0.1 - P 3306 -uroot -p123456;


exit: exit; quit;

SQL specification:

SQL statements are not case sensitive, but the data constants are case-sensitive, the proposed order uppercase, lowercase table name of the library;

SQL statements can be multiple lines describe a single row, ends with; , keyword or simply can not span multiple lines

with spaces and indentation to improve readability statement, usually located in a separate clause of the line, easy to edit, improve readability

Notes: - /*....*/

database operations ( : DDL) statements
show databases; see mysql management database
drop database database name to delete the specified database
create database database name [if not exists] database name to create the database
configuration information check the database when it was created in; Show create database Oldboy

the ALTER database oldboy1 Character set utf-8; encoding modified database

create database if not exists oldboy character set gbk; database set character set

Switch databases use db_name; Note: After entering into a database, no way in the state before returning, but can be switched by use
the SELECT Database () to view the current use of the database


data table operations:

field operations
is not empty and the only not NULL unique
enter target database (use database) to create a data table the cREATE tABLE the Employee
(
the above mentioned id INT pRIMARY kEY AUTO_INCREMENT, set the primary key can not be null, primary key increment (a table is a primary key)
name VARCHAR (25),
Gender boolean, will be automatically converted to TINYINT
TINYINT Age,
Department VARCHAR (20),
salary DOUBLE (7,2)
# create tables, fields of settings
);

view current data show tables of the database table
to view the current data table field information desc employee
will field the current data conversion table table employee to the Create mysql statement Show


# 1. modify table structure alter
Adding a field to the data table: Table ALTER is_married tinyint the Add Employee (. 1)
ALTER the Add Employee Table ENTRY_DATE DATE [constraint field] Not null;


ALTER the Add Employee Table A int, the ADD B VARCHAR (20 is); adding a plurality of fields separated by commas open

alter table employee drop B; delete field B

ALTER Employee table Character Convert to SET UTF8; modified encoding format tables

. Review # 2 - column type modify

uNIQUE not unique weight value field
#modify modified in a field after the field type later
ALTER modify Employee Table Age int (10) After ID Not 18 is default null;


. #. 3 modify - Change the column name
----- modify the column names need to specify the type of the column
alter table employee change department depart varchar ( 20) salary the After


. # 4 modify the table name the rename

the rename the table to the Employee emp;


# 5 drop table drop table tab_name



Table record operation: add - delete - Charles - change

# 1 to increase a data:. Insert into emp (id, age, name, gender, salary, depart) value (1,20, "alex "," 0 ", 5500.1," operation and maintenance unit ");
# insert multiple
iNSERT INTO emp (name, salary, depart) VALUES (" Tang "," 3500 "," development "), (" xiao_yu ", 5000, "Python")

, ( "wang_jun" 8000.02, "operations");
# directly into the
iNSERT INTO emp VALUES (5, "Yuyu" 0,8328.88, "Department of management"), to name a column corresponding to a

#set inserted
iNSERT INTO emp set name = "Danny", Age = 26 is;



. # 2 recorded in table modification TAB_NAME SET field1 = VALUE1 Update Field2 = WHERE ID = value2. 1;

Update the salary SET EMP WHERE ID = 20000 + the salary = 2;




Query current table inside all records from emp * the SELECT;


. # 3 delete table records
DELETE FROM emp; delete all records (one a deletion), and returns control bar number

DELETE FROM emp where id = 5 or id = 3; delete table id 5 and id record 3

truncate table emp_new; use truncate drop table all records
(delete tables, create new tables), the operation does not return the number


# 4. lookup table records the SELECT [DISTINCT] * from table_name
--- from the specified filter from that table, * indicates Find all the columns, you can specify a column ----
---- table clearly know the column you are looking for, distinct to delete duplicate rows ---

select filed1, filed2 from table_name;

# restrictions repeat field
select distinc filed1, filed2 from emp;


# alias
select AS name filed1, filed2 AS Age from table_name;


# filter where clause query
SELECT filed1, where filed2 filed2 from table_name> 80;
! => <> = <= <>

SELECT filed1, filed2 from table_name WHERE filed2 BETWEEN 88 and 100;

SELECT filed1, filed2 from table_name WHERE filed2 in (88,100,200);


SELECT filed1, filed2 from table_name WHERE name like "Y%";
SELECT filed1, filed2 from table_name WHERE name like " y_____ ";
'' '
pattern may% or _,
if% it means that any number of characters,
if a _ indicates a character, '
''

logical operators and or null

SELECT filed1, filed2 from table_name WHERE name =" XXX "and Age = xxxx;

select filed1, filed2 from table_name filed2 the WHERE iS null; empty


row and column names in the table but by the specified sort order columns, sort of, it can be said that the select statement specifies an alias
select filed1, filed2 from table_name where order by filed1 desc; Sort


Key: Select from where group by having order by

the order of execution in the implementation of mysql sql statement: the WHERE from the Select Group by the Order by the HAVING


Group by grouping queries:
- Note: after each group grouped by the grouping condition display only the first record
'' 'where filtration is then filtered before grouping, is HAVING group by (first packet)' ''
--group by clause, you can take multiple thereafter column names, may be with the having clause, group by the results of the screening

#sum aggregate function
SELECT name, SUM (the Django) group by name from oldboy1 HAVING SUM (the Django)> 80;
SELECT name, SUM (the JS) from Employee name by Group;

/ *
both HAVING and where further filtering can be performed on the query results, the difference:
<. 1> statement where only packets before screening, HAVING packet may be used after screening
<2> statement places where use can be replaced haveing
<3> having a polymerization function can be used where not

* /


aggregation functions: the first function is not to be doing polymerisation, requires first the contents of the package and then to check out the polymerization functions can be,
- general inquiries and grouping used in conjunction with

the SELECT SUM (JS) from emp;


# use regular expressions to
the SELECT * from emp emp_name the WHERE REGEXP "^ yu"



# foreign keys
the CREATE TABLE oldboy.classCharger (
# library directly specified below a table
ID TINYINT a PRIMARY KEY AUTO_INCREMENT,
name VARCHAR (20 is),
Age the INT (. 4),
is_married Boolean
);

the INSERT the INTO classCharger (name, Age, is_married) the VALUES ( "Tang", 20,0), ( "Wang ", 26,0), (" Li ", 30,1);

# foreign key
CREATE TABLE Student3 (
TINYINT a PRIMARY KEY AUTO_INCREMENT ID,
name VARCHAR (20 is),
charger_id TINYINT,
a FOREIGN KEY (charger_id) the REFERENCES classcharger (ID)
- # Important associated foreign key must be used as the foreign key and primary key for the associated data type is consistent with a foreing key the sub-table

) ENGINE = INNODB;

the INSERT the INTO Student3 (name, charger_id) the VALUES ( "Zhang", 3), ( "Park", 3);


# increase foreign key
ALTER tABLE Student ADD CONSTRAINT abc fOREIGN kEY (charger_id) REFERENCES classcharger (the above mentioned id);

# delete the foreign key
the ALTER tABLE DROP a fOREIGN kEY Student abc;


#INNODB supported on statements
---- meaning the foreign key pair table: If no candidate key in the parent table, is not allowed in word table INSERT / update

---- meaning foreign key constraints on the parent table: when to update, delete and update corresponding to delete the one or more candidate matches the key in the child table row in the parent table,
the parent table the behavior depends on: specified in the foreign key definition of word tables on update / on delete clauses


are four ways to support --------- ---------- innodb

---------- cascade mode: match update / delete records in the parent table, synchronous update / delete child table records out
cascaded foreign key delete: If the record in the parent table is deleted so History word table is automatically deleted
FOREIGN KEY (charger_id) REFERENCES classcharger ( id) oN dELETE cascade;



when ---------- set null mode update / delete records in the parent table, the sub-match table column set to null record
- foreign key to be noted that the sub-table is not null not



# multi-table queries
join query:
'' '
Create table a (int Primary key ID, name VARCHAR (20 is));

Create table B ( ID int Primary Key, name VARCHAR (20 is), A_ID int);

INSERT INTO A values (. 1, "Tang");
INSERT INTO A values (2, "Yuan");
INSERT INTO A values (. 3, "Wang") ;

INSERT INTO B values (. 1, "sheet",. 1);
INSERT INTO B values (2, "King ", 2);
insert into B values (3, "Li",. 3);

SELECT * from A, B WHERE a.id = b.A_id; inner join query
select A.id, a.name, b.name from a , b where a = b.A_id .id;

'' '

within the connector: inner the Join
SELECT * from the Join a B inner b.a_id = oN and XXXX a.id;



outer connecting: left join: some increase left to the right on the basis of the inner connector no results; right join: increase on the basis of connections, including some of the results are not left to the right;
the SELECT a.name, b.name from the Join a left b = oN b.a_id a.id;


full connectivity: full the Join



# the composite multi-table join query criteria query compound condition table # multiple join query inquiry of

the SELECT the DISTINCT department.dept_name the FROM Employee, Department employee.dept_id the WHERE = department.dept_id
and employee.age> 30;
'' 'the DISTINCT: deduplication unique: only'''


# Plurality of sub-table queries Query
- subqueries nested query is a query statement in another
- the result of the inner query, the query may be provided to the outer query conditions
- a subquery may comprise: IN NOT ANY ALL EXISTS and NOT EXISTS keywords, etc.
- can also contain comparison operators: =, =, <,>, etc.!

---- sub-band-in keyword query, the employee table, but dept_id must. department table appeared in
the SELECT * from emplyoee dept_id in the WHERE (dept_id the SELECT * from department);


# index index features: create and maintain an index will consume a lot of time and disk space, but greatly improve query speed. PRIMARY KEY-- primary key index UNIQUE

the CREATE TABLE test1 (
ID int the AUTO_INCREMENT a PRIMARY KEY,
name VARCHAR (20 is),
Resume VARCHAR (255)
);

the INSERT the INTO test1 (name, Resume) values ( "Alex", "111"), ( "tang", "2222") , ( "zhang", "33333");


alter table test1 modify name varchar (20 ) unique; #unique unique index

to create a regular index
the CREATE TABLE EMP2 (
the above mentioned id int,
name VARCHAR (20),
index index_name (name) # add an index
KEY index_name (name) # add indexes
);

create The only index
the cREATE TABLE EMP3 (
the above mentioned id int,
name VARCHAR (30),
uNIQUE index index_emp (name)
);

create multi-column index of
the cREATE TABLE emp4 (
the above mentioned id iNT,
name VARCHAR (30),
Resume VARCHAR (50),
index_name index (name, Resume)
)

add indexes
the CREATE TABLE T2 the ADD INDEX index_name (the above mentioned id);

the CREATE INDEX index_name ON T2 (the above mentioned id);


delete the index
DROP INDEX index_name on t2;




two: python on the database API --- pymysql

pymysql Import

# database connection
Conn = pymysql.connect (Host = "127.0.0.1", Port = 3306, = User "the root", the passwd = '123456', DB = "Oldboy")

Cursor = conn.cursor (Cursor = pymysql .cursors.DictCursor)
SQL = "Create Table Tang (ID int (10), name VARCHAR (20 is))"

# the cursor.execute (SQL)
RET = the cursor.execute ( "INSERT INTO Tang values (. 1, 'Alex') , (2, 'Yuan') ")
#Print (RET) returns the number of rows affected #

# RET2 the cursor.execute = (" SELECT * from Tang; ")
# Print (RET2)
#
# # Print (cursor.fetchone ( )) query data cursor marks the current cursor location query
# # Print (cursor.fetchall ())
# Print (cursor.fetchmany (2))
#
# cursor.scroll (. 1, MODE = "relative") # setting position of the cursor


conn.commit # ()
# the Cursor.close()
# conn.close()


'''
! # / usr / bin / Python the env
# - * - Coding: UTF-. 8 - * -
Import pymysql

# create a connection
conn = pymysql.connect (host = '127.0.0.1 ', port = 3306, user = 'root', = the passwd '123', DB = 'T1')
# create a cursor
cursor = conn.cursor ()

# execute SQL, and returns the number of rows affected close
effect_row = cursor.execute ( "update hosts set host = '1.1.1.2'" )

# execute SQL, and returns the number of rows affected
#effect_row the cursor.execute = ( "Host = SET Update the hosts '1.1.1.2' WHERE NID>% S", (. 1,))

# execute SQL, and returns the affected rows number
#effect_row = cursor.executemany ( "INSERT INTO the hosts (Host, COLOR_ID) values (% S,% S)", [( "1.1.1.11",. 1), ( "1.1.1.11", 2)])


# submit, or can not save new or modified data
conn.commit ()

# close the cursor
cursor.use Close ()
# close the connection
conn.Close ()
3, to obtain data from the newly created by ID
You can get the latest auto-incremented ID, which is inserted at the end of a data ID

# / usr / bin / env Python!
# - * - Coding: UTF-8 - * -
Import pymysql

conn = pymysql.connect (Host = '127.0 .0.1 ', Port = 3306, = User' the root ', the passwd =' 123 ', DB =' T1 ')
Cursor = conn.cursor ()
cursor.executemany ( "INSERT INTO the hosts (Host, COLOR_ID) values (% S ,% S) ", [(" 1.1.1.11 ",. 1), (" 1.1.1.11 ", 2)])
conn.commit ()
cursor.close ()
conn.Close ()

'' '

Guess you like

Origin www.cnblogs.com/tangcode/p/12155177.html