day 43 python link MySQL (injection), the transaction, View, functions, stored procedures, triggers]

pymysql (Python operations MySQL)

import pymysql
conn = pymysql.connect(
host='localhost',
user='root',
password='999',
database='db1',
charset='utf8'
)
cursor = conn.cursor(pymysql.cursors.DictCursor)
sql = "insert into t8 (name,email) values (%s,%s)"
data = []
for i in range(3000000):
num = random.randint(0, 3000000)
data.append(('root%s' % num, 'root%[email protected]' % num))

cursor.executemany(sql, data) #执行多条
cursor.execute(sql,(data)) # 执行一条
conn.commit()
cursor.close()
conn.close()

Note:
. A conn, the Cursor run out of resources needed to close the connection
. B query time, fetchone, fetchmany, fetchall, default returns a tuple, you need to return to dictionary words: cursor = conn.cursor (cursor = pymysql.cursors.DictCursor )
c. deletion and update when needed after execute, add conn.commit ()

Today's content:

PyMySQL: (*******************************)

. A login authentication

write sql statement when the% by value of time , requires quotes:
sql = "SELECT * from T4 WHERE name = '% S' and pwd = '% S'"% (username, pwd)

risk brought sql statement above is:

Example a:
username = Zekai ' #

the SELECT * from T4 the WHERE name = 'Zekai' # 'and pwd =' '

Example two:
username = dbsahvbdsha' or 1 = 1 #
the SELECT * name = the WHERE from T4 'dbsahvbdsha' or 1 = 1
occurs above problems, we called SQL injection (**********************************)
the root of the problem is:
  because too trust user input, lead us to accept user input parameters of time, and no escape for him
  to solve the SQL injection:
    1. own hand to escape the value entered by the user
    2. use the execute () automatically filter
      sql = "select * from t4 where name = % s and pwd =% s"

      cursor.execute(sql,(username, pwd))

Insert a: cursor.execute (sql, ( 'lxxx', '1234'))

Insert multiple:
  Data = [
    ( 'AAAAA', 'AAA'),
    ( 'bbbb', 'BBB'),
    ( 'FFFF', '666'),
    ( 'rrrr', '888'),
      ]
Cursor. executemany (SQL, Data)

the try:
  the cursor.execute (SQL, ( 'LXXX', '1234'))

  Delete, and update when things need to submit
  conn.commit ()
the except Exception AS E:
  conn.rollback ()
cursor.lastrowid: the last line number

transactions: (************** ************************************************** **********************************)

A set of actions either succeed or fail

properties:
  Atomic: a set of operations, either all succeed or fail
  consistency (Consistency): refers to transactions that occurred before and after the occurrence of the total data still matches the
  isolation (Isolation ): simply put, the operation of a transaction are not visible to other transactions
  persistent (durability): when the transaction is completed, its impact should be retained, can not be undone, can only be offset by "other things, opened a" before error

scenario:
  thinking:
    I go to the bank to a friend remittances,
    there are 1000 yuan on my card,
    500 yuan a friend card,
    my friend transfer 100 yuan (no fee),
    if, cable broken, my money just buckle, the friend was not any money in overtime, how do?
the Create the Table T11 (
  the above mentioned id int Primary Key AUTO_INCREMENT,
  name VARCHAR (32) not null default '',
  money int not null default 0
  ) = Engine Innodb charset = utf8;

INSERT INTO T11 (name, money) values ( ' zekai', 1000), ( 'eagon', 500);

solution:
  open Services (transaction Start)
  (operation performed sql)
  commit: submit the above SQL, let it take effect
  rollback: Rollback
  show full tables; All types
----------------------------- ---------------------------------------------

the following understanding:
a view:
  the causes:
    If there is a frequent SQL statement will be used to, for example:
    select * from t4 where id> and ID 12 is <24;
    engage in a map, or an alias
    select * from t4 where id> 12 and id <24 ===> v1

  View: select * from v1;

  创建视图:create view v1 as select * from t4 where id>12 and id <24;

  Modify view: alter view v1 as sql statements;
  deleted view: drop view v1;

  question:? If the native table data has changed, will not change that view will change
    generally does not modify individual data view, but or can be changed

    update test set name='jerry';

    update v1 set name='owen';

  Application scenarios:
    MySQL: (DBA)
    generated view View
  program: select * from v1 calls;

Second, the function: Do not use
  in the program, calculated by the code, calculate, and then passed to the SQL statement executed


Third, the stored procedure: a bunch of SQL statements package, similar to the function, the result is a stored procedure
  MySQL server:
  DBA (write)
  A simple stored procedure:.
    DELIMITER //
    the Create Procedure p1 ()
    BEGIN
    the SELECT * from T11 ;
    END //
    DELIMITER;
   program call a stored procedure: call p1 ();


  b. 传参数: (in)
    delimiter //
    create procedure p2(
    in n1 int,
    in n2 int
    )
    BEGIN
    select * from t11 where id > n1;
    END //
    delimiter ;

    Program stored procedure calls: Call P2 (12 is, 2)

  C pass parameters: (OUT).
   DELIMITER //
   Create Procedure P3 (
   in N1 int,
   OUT N2 int
   )
   the BEGIN
   SELECT * WHERE ID from T11> N1;
   SET N2 = . 1;
   the END //
   DELIMITER;

   V2 = 123212 @ SET;  # define variables

   p3 Call (12, @ v2);
   the SELECT @ v2;  # sql statement to see whether the

four triggers: meet at a particular table add, delete, change, the automatic trigger function called trigger [ adding a table to a user data while in the log table also add a record]

  delimiter //
  CREATE TRIGGER t1 BEFORE INSERT ON t7 FOR EACH ROW
  BEGIN
  insert into t11 (name, money) values ('xxx', 1234);
  END //
  delimiter ;

You may use as a trigger? 
Trigger specifically for our data add insert, delete to delete a certain table, change the update behavior,
perform such acts execution will trigger once a trigger that automatically runs another section of code sql

create trigger syntax
# for insertion
create trigger tri_after_insert_t1 after insert on the each table Row for
the begin
SQL Code ...
End

the Create the Trigger tri_before_insert_t2 the before INSERT ON table name the each Row for
the begin
SQL Code ...
End

# for deleting
create trigger tri_after_delete_t1 after delete on the each table name Row for
the begin
sql Code ...
End

the Create the Trigger tri_before_delete_t2 the before the Delete ON table name for each row
the begin
sql Code ...
End

# modifications to
create trigger tri_after_update_t1 after update on the table name for each row
begin
sql 代码...
end

create trigger tri_before_update_t2 before update on 表名 for each row
begin
sql 代码...
end

Guess you like

Origin www.cnblogs.com/qingqinxu/p/11040133.html