Basic SQL database operations, the data written using python the excel database, or read out from the library

First, tell us about some of the basic operation of SQL database:

1 Create 2 Delete 3 4 written update (modify) 5 Select condition

With the above basic operation, you can create and store up a simple database.

 

Release the code to call the python: here is to call dos not as good as the following simple database operation

# - * - Coding: UTF-. 8 - * - 
"" " 
the Created Mon ON. 6 On May 2019 09:59:32 

@author: wenzhe.tian 
" "" 


Import MySQLdb 

# Open Database Connectivity 
DB = MySQLdb.connect ( " localhost " , " the root " , " twz1478963 " , " the TESTDB " , charset = ' UTF8 ' )  
 # using the cursor () method to get the cursor operation 
cursor = db.cursor () 

# if the data table already exists using execute () method to delete table. 
cursor.execute ( ")
print(cursor.fetchone())
cursor.execute("SELECT VERSION()")


# 创建数据表SQL语句
sql = """CREATE TABLE EMPLOYEE (
         FIRST_NAME  CHAR(20) NOT NULL,
         LAST_NAME  CHAR(20),
         AGE INT,  
         SEX CHAR(1),
         INCOME FLOAT );"""

cursor.execute(sql)

### %\ 替换
sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES (%s, %s, %s, %s, %s );" % \
       ("'Mac'", " 'Mohan' " , 20, " 'M' " , 9000 ) 
         
         
         
the try :
    # execute sql statement 
   cursor.execute (sql)
    Print (cursor.fetchone ())
    # submitted to the database to perform 
   the db.commit ()
 the except :
    # Case there IS in the any ROLLBACK error 
   db.rollback () 
   
# ##% \ Alternatively 
SQL = " the INSERT the INTO the EMPLOYEE (FIRST_NAME, \ 
       the LAST_NAME, of AGE, SEX, INCOME) \ 
       the VALUES (% S,% S,% S,% S ,% S); " % \ 
       ( " 'John' ", " 'By Will' " , 24-, " 'M' " , 12000 ) 
         
         
         
the try :
    # execute sql statement 
   cursor.execute (sql)
    Print (cursor.fetchone ())
    # submitted to the database to perform 
   the db.commit ()
 the except :
    # Rollback Case there IS the any error in 
   db.rollback () 
   
   
SQL = " the SELECT * the FROM the EMPLOYEE \ 
       the WHERE FIRST_NAME like S% " % ( " '% H_' " ); 
       
'' ' 
the WHERE A and / or B in BETWEEN (A, B ) 
% value represents a plurality of characters, a character _ underlined; 
M%: to be able wildcards, regular expressions, fuzzy intention to query information for the beginning of M.
% M%: indicates that the query contains all the content of M. 
% M_: M represents a query to all the content in the penultimate position of 
'' ' 
       
# DELETE the FROM the EMPLOYEE the WHERE AGE <20        
       
the try :
    # execute SQL statements 
   cursor.execute (SQL)
    # get a list of all the records 
   Results = cursor.fetchall ()
    for Row in results: 
      fname = Row [0] 
      lname = Row [. 1 ] 
      Age = Row [2 ] 
      Sex = Row [. 3 ] 
      Income = Row [. 4 ]
       # printing result 
      Print ( "fname=%s,lname=%s,age=%s,sex=%s,income=%s" % \
             (fname, lname, age, sex, income ))
except:
   print ("Error: unable to fecth data")
   
# 关闭数据库连接
db.close()
View Code

 

SQL language to write the above code is about to form characters and call the operator interface.

Some examples of storage to put new database excel as the following reference: calling here to_sql dataframe operate Note that the encoding = 'gbk' in Chinese Transformation.

When you create a form name does not need advance written to the database.

# -*- coding: utf-8 -*-
"""
Created on Tue May  7 15:40:23 2019

@author: ext.wenzhe.tian
"""


from sqlalchemy import create_engine
import pandas as pd

host = '127.0.0.1'
port= 3306
db = 'beilixinyuan'
user = 'root'
password = 'twz1478963'

engine = create_engine(str(r"mysql+mysqldb://%s:" + '%s' + "@%s/%s?charset=utf8") % (user, password, host, db))



try:
#   df = pd.read_csv(r'D:\2PHEV_v3.csv',encoding='gbk')
#   读取  
    table='sale_phev'
    sql = "SELECT * FROM "+'%s' %(table)
    df=pd.read_sql(sql,con=engine)
#    写入
#    df.to_sql('sale_ev', con=engine, if_exists='append', index=False)
except Exception as e:

    print(e.message)
    


#The method of deriving 2 
# '' ' 
# the WHERE A and / or B in BETWEEN (A, B) 
# % values represent a plurality of characters, a character _ underlined; 
# M%: to be able wildcard, regular expression represented by meaning fuzzy query information for the beginning of M. 
# % M%: indicates that the query contains all the content of M. 
# % Of M_: M represents a query to all the contents in the penultimate position of the 
# '' ' 
# 
# 
# 
Import MySQLdb
 Import PANDAS PD AS
 # Open Database Connectivity 
DB = MySQLdb.connect ( " localhost " , " the root " , " twz1478963 " , " beilixinyuan " , charset = '' )  
 # Using the cursor () method to get the cursor operation 
Cursor = db.cursor (cursorClass = MySQLdb.cursors.DictCursor) 


SQL = " the SELECT * sale_ev the FROM " 
       

# the DELETE the FROM of AGE the EMPLOYEE the WHERE <20 is        
       
the try :
    # execute SQL statements 
   cursor.execute (SQL)
    # get a list of all the records 
   Results = cursor.fetchall () 
   pd.read_sql (SQL, CON = Engine) 
 
the except :
    Print ( " Error: Unable to fecth the Data " ) 
   
H = list (Results) 
df =pd.DataFrame(h)
del results
del h
View Code

 

Guess you like

Origin www.cnblogs.com/techs-wenzhe/p/10819289.html