#!/usr/bin/env python#-*-coding:utf-8-*-# @Time: 2017/11/20 16:03# @Author: lijunjiang# @File: Demo.pyimport MyS qldb# Connection Database # Host database ip# Port database Listener # User Database user # passwd users password # DB database name # CharSet character Set default uft-8# MySQLdb.connect method #comn=mys Qldb.connect (host= "11.11.11.11", user= "Python", passwd= "Python", db= "Python", charset= "UTF8", port=3306) # function Type Def Connect_mysql (): Db_config = Dict (host= "11.11.11.11", port=3306, db= "Python", charset= "UTF8", user= "Python", passwd= "p Ython ") Try:cnx = MySQLdb.connect (**db_config) except Exception as Err:raise err return cnxif __n ame__ = = "__main__": sql = "CREATE TABLE test (ID int not null);" CNX = Connect_mysql () # connect MySQL CNS = cnx.cursor () # Create a Cursor object # print (dir (CNX)) Try:cns.execute (SQL) # Execute SQL Execute executes a statement cns.close () # Close Cursor cnx.commit () # commit operation except Exception as err: Raise Err Finally:cnx.close () # Close Connection # execute multiple words sql_many = ' insert into Test (ID) value (%s); ' param = [] for i in Xrange (90,101): Param.append ([Str (i)]) # print (param) CNX = connect_mysql () cus = Cnx.cursor () Try:cus.executemany (Sql_many,param) # Executemany () receives an SQL statement, a list # print (dir (cus)) Cus.close () except Exception as Err:raise err Finally:cnx.close () # get execution result sql_select = ' Select * from Test; ' CNX = Connect_mysql () cus = Cnx.cursor () try:cus.execute (sql_select) Result_one = Cus.fetchone () # Fetchone () Gets a result print ("RESUTL1 {0}", Format (result_one)) Result_many = Cus.fetchmany (3) # Fetchmany (n) Get n result Print ("RESUTL1 {0}", Format (result_many)) Result_all = Cus.fetchall () # Fetchall () Get all results Print ("RESUTL1 {0}", Format (Result_all)) Cus.close () except Exception as Err:raise err finally: Cnx.close ()
mysql> select * from test;+-----+| id |+-----+| 90 || 91 || 92 || 93 || 94 || 95 || 96 || 97 || 98 || 99 || 100 |+-----+11 rows in set (0.00 sec)
Python operations database for connection, execute SQL statement