Se ha denunciado esta presentación.
Se está descargando tu SlideShare. ×

Python Programming1.ppt

Próximo SlideShare
Cargando en…3

Eche un vistazo a continuación

1 de 99 Anuncio

Más Contenido Relacionado

Similares a Python Programming1.ppt (20)

Más reciente (20)


Python Programming1.ppt

  1. 1. Python Programming ASDT
  2. 2. Introduction • Python was conceived in the late 1980s and its implementation was started in December 1989 by Guido van Rossum at CWI (National Research Institute for Mathematics and Computer Science, located at the Science Park Amsterdam in the Netherlands) • Python 2.0 was released on 16 October 2000, with many major new features including a full garbage collector and support for unicode.
  3. 3. • Python 3.0, a major, backwards-incompatible release, was released on 3 December2008 after a long period of testing. • Many of its major features have also been back ported to the backwards-compatible Python 2.6 and 2.7.
  4. 4. • Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. • Python's syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C, and the language provides constructs intended to enable clear programs on both a small and large scale.
  5. 5. • Python supports multiple programming paradigms, including object-oriented, imperative and functional programming styles. • It features a fully dynamic type system and automatic memory management, similar to that of Scheme, Ruby, Perl and Tclm and has a large and comprehensive standard library. • Like other dynamic languages, Python is often used as a scripting language, but is also used in a wide range of non- scripting contexts. • Using third-party tools, Python code can be packaged into standalone executable programs. Python interpreters are available for many operating systems.
  6. 6. features • Python is a general-purpose(not domain-specific), high-level programming language • Design philosophy of Python emphasizes code readability • Python combine remarkable power with very clear syntax • Python standard library is large and comprehensive • Its use of indentation for block delimiters is unique among popular programming languages • Python supports multiple programming paradigms , primarily but not limited to object-oriented, imperative and, to a lesser extent, functional programming styles. • It features a fully dynamic type system and automatic memory management, similar to that of scheme Ruby, Perl and Tcl.
  7. 7. • Python is used as a scripting language but is also used in a wide range of non-scripting contexts. • Python interpreters are available for many operating systems. • The reference implementation of python is free and open source software and has a community-based development model • Cpython is managed by the non-profit Python Software Foundation • Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage collector for memory management. • An important feature of Python is dynamic name resolution (late binding), which binds method and variable names during program execution.
  8. 8. Python language implementations • CPython is the default, most-widely used implementation of the python programming language, its written in C. • Jython successor of JPython, is an implementation of the Python programming language written in Java. • Jython includes almost all of the modules in the standard Python programming language distribution Jython compiles to Java Byte Code. • IronPython is an implementation of the Python programming language targetting the .Net Framework.
  9. 9. Zen of python • Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down. • Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator for Life (BDFL).
  10. 10. Zen of python… • The core philosophy of the language is summarized by the document "PEP 20 (The Zen of Python)", which includes aphorisms such as…. • PEP contains the index of all “Python Enhancement Proposals”, known as PEPs. PEP numbers are assigned by the PEP editors, and once assigned are never changed. • Latest Pep number is 208 specifies the Reworking the Coercion Model.
  11. 11. Zen… •Beautiful is better than ugly. def gcd(a,b): while b != 0: a, b = b, a % b return a •Explicit is better than implicit. File openings are not that explicit, The : in Python is lovely and explicit •Simple is better than complex. Something simple is easily knowable Something complex is not Automatic memory management means code is simpler That we can define getter/setters and override existing ones in Python is awesome. Getting length of objects is simple in python: l = [1,2,3,4,5,6,7,8] len(l)
  12. 12. • Complex is better than complicated. • Flat is better than nested. Inheritance flattening Keep object inheritance shallow Multiple inheritance keeps things shallow but things get more complex Break up complex structure Keep your if/elif/else use as light as possible Smaller code == Better code • Sparse is better than dense. Is this a style guide thing? whitespace? naming standards
  13. 13. • Readability counts. Readability is the number 1 reason why organizations select Python if (x == y); { // logic }; // a day wasted • Special cases aren't special enough to break the rules. Everything is an object
  14. 14. • Although practicality beats purity Sometimes the rules need to be broken: >>> class Two(int): ... pass ... >>> print(Two(1)) 1 >>> Two.__str__ = lambda x: '2' >>> print(Two(1)) 2 • Errors should never pass silently Errors should not be fatal Don’t blame the user for bugs in Python • Check out except Exception at the bottom! logging.exception(error) captures the entire error to the logs! try: handle_a_client() except socket.error, e: log.warning('client went away: %s', e) except Exception, e: logging.exception(e) # This captures the whole traceback!!!
  15. 15. • In the face of ambiguity, refuse the temptation to guess. 1 + '1' # blows up in Python, not in other languages # We like this behavior! Also, remove the ambiguity and whack some parenthesis • There should be one - and preferably only one- obvious way to do it – Protocols: • DB API • WSGI • File API
  16. 16. • Although that way may not be obvious at first unless you’re Dutch – Guido can be quirky – Community feedback keeps BDFL in check • Now is better than never – Fix the problem now – Try it in your shell, and your tests – Perfection is the enemy of the good – Python 3 was years in the making, but much less than Perl 6. • Although never is often better than right now. – Things that ain’t gonna happen – Adding ‘?’ to identifiers in Python
  17. 17. • If the implementation is hard to explain, it’s a bad idea. – If you can’t say it, don’t do it • If the implementation is easy to explain, it may be a good idea. – Just because you can explain your idea, if it has no point then it shouldn’t be included. • Namespaces are one honking great idea – let’s do more of those! – locals > nonlocals > globals > builtins – Me (pydanny) loves this about Python
  18. 18. Python interpretter • Invoking python interpreter • The interpreter is usually installed as /usr/bin/python • On windows ..C:python27 • Set path=%path%;C:python27 • End of file character is control-Z on win ,in linux it is ctrl-D
  19. 19. Zen in conclusion • Unless explicitly silenced. In the facse of ambiguity, refuse the temptation to guess. • There should be one-- and preferably only one --obvious way to do it. • Although that way may not be obvious at first unless you're Dutch. • Now is better than never. Although never is often better than *right* now. • If the implementation is hard to explain, it's a bad idea. • If the implementation is easy to explain, it may be a good idea. • Namespaces are one honking great idea -- let's do more of those!
  20. 20. • Argument Passing:- Use sys.argv to retrieve arguments – Sys.argv[0] is the python command file name – Sys.argv[1] is the first argument – Sys.argv[2] the second argument etc
  21. 21. #argument passing Import sys Print “Number of arguments”,len(sys.argv) If len(sys.argv) > 1: print “first arguement”, sys.argv[1] else: print “No argument passed”
  22. 22. Executable python scripts • On unix systems, python can be made directly executable, like shell scripts, by putting the line #! /usr/bin/env python • Use command “chmod +x” to make python file as executable file • #! /usr/bin/env python Print “hello world”
  23. 23. Source code encoding • For using non ASCII charactors in your python program use # -*- coding: iso-8859-1 -*- #! /usr/bin/env python # -*- coding: iso-8859-1 -*- print “hello world”
  24. 24. Python Data types • In python every thing is an object, including a numeric value is also an object • Variable is a place holder to store anything for example a=7 b=893.34 c=”hello world” d=[45,78,”hello”] e=MyClass() f={'name':,'jack','age':,18}
  25. 25. Numbers Myvar=7 Myvar=433.89 myvar=343434343L Expression Myvar=78*(32+34) +34**3
  26. 26. • String mystring='hello' • mystring1=”hello world” • Mystring2=”””hello world””” • Mystr='''hello world''' >>>len(mystr) >>>mystr.upper() >>>mystr.title() 'Hello World' >>>mystr.split(' ') ['Hello','World'] >>>mystr.zfill(20) '000000000Hello World' >>mystr.rjust(12) ' Hello World' >>>mystr.ljust(12) 'Hello World '
  27. 27. • myvar=”hello world” >>>myvar[0] 'H' >>>myvar[1] 'e' >>>myvar[8] 'r' >>>myvar[-1] 'd' >>>myvar[-2] 'l' >>>myvar[2:] 'llo world” >>>myvar[5:] “ world” >>>myvar[:-2] “hello wor” >>>myvar[2:-2] 'llo wor” • Myvar*3 'Hello worldHello worldHello world' • Myvar + “ok123” 'Hello Worldok123'
  28. 28. Myvar='Hello World' Print myvar.upper() #HELLO WORLD Print myvar*2 #”Hello worldHello World” Print myvar.split(' ') # ['Hello','World'] a=myvar.lower().replace(' ', '') Print a*4 # helloworldhelloworldhelloworldhelloworld
  29. 29. List >>>lst=['29',34.43,'grabber',95] >>>lst[2] #'grabber' >>> del lst[2] # removes item 2 >>>lst #['29',34.43,95] >>>lst.append('help') >>>lst #['29',34.43,95,'help'] >>>lst[0] # '29' >>>lst[-1] #'help' >>>lst[1:-1] #[45,2] >>>lst*2 #['29',34.43,95,'help','29',34.43,'help'] >>>lst +[100,200] #['29',34.43,'help',100,200]
  30. 30. List Methods append(x) Add x to the end of the list extend(L) Add all items in sequence L to the end of list insert(i,x) insert x at a position i remove(x) remove first item equal to x pop(i) remove item at position i Pop() remove item at the end of list index(x) return index of first item equal to x count(x) count occurances of x
  31. 31. Dictionaries >>> a={'abc':24.5,'mo': 'fo', 'answer':90} >>>a['abc'] #24.5 >>>a['mo'] #'fo' >>>a['answer'] #90 >>>a.keys() #['answer','mo','abc'] >>>a.values() #[90,'fo',24.5] >>>a.has_key('abc') #True >>>a.has_key('xyz') #false >>>a.get('abc',0) #24.5 >>>a.get('xyz'0) +0 >>>a.items() #[('answer',90),('y',77),('mo','fo'),('abc',24.5)]
  32. 32. >>>a #{'answer':90,'mo':'fo','abc':24.5} >>>a.update({'x':67,'y':77}) >>>a #{'answer':90,'y':77,'mo':'fo','abc':24.5,'x':67} >>>dir(a) # can apply on the dictionary a ['clear','copy','fromkeys','get','has_key','items','i teritems','iterkeys','itemvalues','keys','pop','p opitem','setdefault','update','values','viewite ms','viewkeys','viewvalues']
  33. 33. >>>a.pop('x') #67 >>>a #{'answer':90,'y':77,'mo':'fo','abc':24.5} >>>a.pop('y') #77 >>>a {'answer':90,'mo':'fo','abc':24.5}
  34. 34. Input Output Print Print 'Hello' Print 'world' Print 'hello world'
  35. 35. input a=input(“enter an integer value:”) #Enter an integer value:89 Print a #89 >>> a=raw_input(“enter a string:”) #Enter a string:Python >>>Print a #python
  36. 36. format Python uses c language printf style to format strings,use the same syntax of printf for string formating >>>a=”Name=%s and age=%d” %('jack',19) >>>Print a #Name=Jack and age=19
  37. 37. Built in functions >>>dir() ['__builtins__','__doc__','__name__','__package__'] >>>dir(__builtins__) ['abs','all','any','apply','basestring','bin','bool','buffer','bytearray', 'bytes','callable','char','classmethod','cmp','coerce','compile',' complex','copyright','credits','delattr','dict'.................... ......... ]
  38. 38. Builtins-continued >>>round(7.6) #8.0 >>>round(7.4) #7.0 >>>abs(-78) #78 >>int(“67”) #67 >>>len(“hello world”)#11 >>>min(78,6,3,4,90) #3 >>>max(78,6,3,4,90) #90 >>>range(10) # [0,1,2,3,4,5,6,7,8,9] >>>range(10,20)
  39. 39. >>>a=78 >>>b=90 >>>c=eval(“a+b”) >>>c #168 >>>basket=['apple','orange','apple','pear','orange','banana'] >>>list(set(basket)) ['orange','pear','apple','banana'] >>>questions=['name','quest','favourite color'] >>>answers=['lancelot','the holy grail','blue'] >>>zip(questions,answers) [('name','lancelot'),('quest','the holy grail'),('favorite color','blue')]
  40. 40. The for loop The for loop in python has the ability to iterate over the items of any sequence such as a list or a string. For i in range(6): Print i ##0 1 2 3 4 5 For i in range(1,10,2): Print i # 1 3 5 7 9
  41. 41. A=['alpha','beta','gama','delta']: For i in a: Print i # alpha beta gama delta For i in range(100): if i < 50: continue print i if i ==55: break # 50 51 52 52 53 54 55
  42. 42. a=['tic','tac','toe'] for i,v in enumerate(a): Print i, v # 0 tic #1tac #2toe X=1 While true: if x>10: break print x x=x+2 # 1 3 5 7 9
  43. 43. a=[[1,2,3],[4,5,6],[7,8,9]] for list in a: For x in list: print x # 1 2 3 4 5 6 7 8 9 string=”hello world” for x in string: print x # h e l l o w o r l d import time start =time.clock() for x in range(1000000): pass stop = time.clock()
  44. 44. While :-The while loop continues until the expression becomesfalse.the expression has to be a logical expression and must return either a true or a false value. While expression: statement(s) #! /usr/bin/python count=0 while (count<9): print 'the count is :' , count count =count+1 Print “good bye!”
  45. 45. Functions • Python everything is an object • A callable object is an object that can accept some arguments(parameters) and return an object. • Functions can be stored in any variable,list or dictionary,just like integers in c language • A function is the simplest callable object in python
  46. 46. Function definition Def hello1(): Print “hello world” Return Def hello2(): ***hello world function*** Print “hello world” Return Hello1() Hello2()
  47. 47. Function is a value which can be stored in any variable a=hello1 b=hello2 a() b() Print dir(b) Print b.func_name Print b.func_doc
  48. 48. • Function Arguments • You can call a function by using the following types of formal arguments:- • Required arguments • Keyword arguments • Default arguments • Variable-length arguments
  49. 49. • Syntax • Def functionname(parameters): “function-docstring” function-suite return expression Ex: Def myfn(a,b): C=a*b Return c D=myfn(8,9) Print d
  50. 50. Function with default value • Def myfn(a,b=7): C=a*b return c D=myfn(8,9) Print d E=myfn(8) Print e
  51. 51. Function with variable number of arguments Def print (format,*args): out=format % args Print out Printf(A=%08.3f b=%d c=%dn”,34.89,56,78) # a=0034.890 B=56 c=78 Def pr(*a): Print len(a) Print a Pr(67,78) Pr(6,8,9) # 2 (67,78) 3 (6,8,9)
  52. 52. Function with keyword arguments Functions can also be called keyword arguments of the form keyword=value. Def mydict(var,**dict): Print “var :” var keys=dict.keys() values=dict.values() Print keys Print values Return Mydict(78,alpha=34,beeta=89,gama='koil') #var:78 ['alpha','beeta','gama'] [34,89,'koil']
  53. 53. Function can return more than one value:- Def xyz(a,b): c=a+b d=a-b e =a*b return c,d,e x,y,z=xyz(5,6) Print x Print y Print z#11 -1 30
  54. 54. Anonymous functions You can use the lambda keyword to create small anonymous functions.These functions are called anonymous because they are not declared in the standard manner by using the def keyword Syntax Lambda[arg1 [,arg2,…..argn]]:expression
  55. 55. • Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter(), map() and reduce().
  56. 56. • #!/usr/bin/python • # Function definition is here sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) • This would produce following result: Value of total : 30 Value of total : 40
  57. 57. • Ex:2 • >>> def make_incrementor (n): return lambda x: x + n >>> >>> f = make_incrementor(2) >>> g = make_incrementor(6) >>> >>> print f(42), g(42) o/p :44 48 >>> >>> print make_incrementor(22)(33) 55
  58. 58. • Ex3:>>> def make_incrementor (n): return lam bda x: x + n >>> >>> f = make_incrementor(2) >>> g = make_incrementor(6) >>> >>> print f(42), g(42) 44 48 >>> >>> print make_incrementor(22)(33) 55
  59. 59. Date and time • Time module:- in time module the function time.time() returns the current system time in ticks since 12.00am,Jan 1 1970.The “tick” floating-point numbers in units of seconds. • Import time ticks=time.time() print “number of ticks since 12:00am,january 1,1970:”,ticks
  60. 60. Getting current time • Import time Localtime=time.localtime(time.time()) Print list(localtime) Output can be in the following mode 2012,02,07,12,30,3,328,0]
  61. 61. Index field values 0 4-digit year 2008 1 Month 1 to 12 2 Day 1 to 31 3 Hour 0 to 23 4 Minute 0 to 59 5 Second 0 to 61(60 or 61 are leap- seconds) 6 Day of Week 0 to 6(0 is Monday) 7 Day of Year 1 to 366(julian day) 8 Daylight savings -1,0,1,-1 means library determines DST
  62. 62. How to install modules • In linux tar –zxvf module-name.tar.gz cd module-name python install
  63. 63. classes • Compared with other programming languages,Pythons class mechanism adds classes with a minimum of new syntax and semantics. • Python classes provides all the standard features of object oriented programming • The class inheritance mechanism allows multiple base classes • A derived class can override any methods of its base class or classes
  64. 64. • A method can call the method of a base class with the same name. • Objects can contain arbitrary amounts and kinds of data • Class are created at runtime, and can be modified further after creation • In c++ terminology,normally clas members are public • All member functions are virtual
  65. 65. • Classes themselves are objects.This provides semantics for importing and renaming • Built-in types can be used as base classes for extension by the user. • Most built-in operation with special syntax(arithemetic,subscripting) can be redefined for class instances.
  66. 66. • class HelloWorld: def __init__(self): self.outText = "Hello World" def printOut(self): print self.outText myHelloWorld = HelloWorld() myHelloWorld.printOut()
  67. 67. • When the object instance "myHelloWorld" of object type "HelloWorld" is initialized (where "myHelloWorld" is assigned as type "HelloWorld") the initializer is called, in this case setting "self.outText" to "Hello World". If you've ever used C++, it's a constructor. You use it to create the initial conditions that the object should have (default values and such). It can also take parameters after "self" like any other function.
  68. 68. • Just as a side note: self is actually just a randomly chosen word, that everyone uses, but you could also use this, foo, or myself or anything else you want, it's just the first parameter of every non static method for a class. This means that the word self is not a language construct but just a name
  69. 69. • >>> class A: ... def __init__(s): ... s.bla = 2 ... >>> >>> a = A() >>> a.bla 2
  70. 70. The constructor and destructor functions
  71. 71. Regular Expression
  72. 72. Regular Expression • Regular expressions are also called Res or regexes or regex patterns. • They are essentially a tiny, highly specialized programming language embedded inside python and made available through the re module • They uses some special characters for pattern matching
  73. 73. • A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. • The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression. • We would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'.
  74. 74. Special characters • ‘.’(dot) in the default mode, this matches any character except a newline. If the dotall flag has been specified, this matches any character including newline. • ‘^’(caret) matches the start of the string, and in multiline mode also matches immediately after each newline. • ‘$’ matches the end of the string or just before the newline at the end of the string, and in multiline mode also matches before a newline.
  75. 75. • ‘*’ causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match a, ab or a followed by any number of b’s • ‘+’ causes the resulting RE to match 1 or more repetitions of the preceding RE.ab+ will match a followed by any non-zero number of b’s;it will not match just a. • ‘?’ causes the resulting RE to match 0 or 1 repetitions of the preceding RE
  76. 76. • {m}: Specifes that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five • {m,n}: causes resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m species a lower bound of zero, and omitting n species an infinite upper bound.
  77. 77. • number:- matches the contents of the group of the same number. For example, (.+)1 matches the ‘the the’ or ‘55 55’, but not ‘ the end’ string. • d :- when Unicode flag is not specified ,matches any decimal digit ; this is equivalent to the set [0-9]. • s :- when Unicode flag is not specified ,matches any white space character. • s$:-when LOCALE and unicode flags are not specified ,matches any non-white space character.
  78. 78. • w:-matches any alphanumeric character and the underscore. Equivalent to the set of [a-z A- Z 0-9 _] • Findall :-It searches all patterns and returns as a list. • Ex: • >>> import re • >>>a=“hello 234789 world 63678 ok 1 ok 1115 alpha 88 beta 999g” • re.findall(“d+”,a) results all digits from the above string.
  79. 79. • D is any character other than numeric character • D+ matches data other than ‘numeric data’ • Re.findall(“D+”,a) results all data other than numeric data. • {2,} matches two or more numeric characters • "[ai]" represent any one of the character 'a' or 'i' • "p[ai]t" matchs pat or pit
  80. 80. Matching and searching • Python offers 2 different primitive operations based on regular expressions :match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string.
  81. 81. The match Function • This function attempts to match RE pattern to string with optional flags. Here is the syntax for this function − re.match(pattern, string, flags=0) Here is the description of the parameters: Parameter Description pattern This is the regular expression to be matched. string This is the string, which would be searched to match the pattern at the beginning of string. flags You can specify different flags using bitwise OR (|). The re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression.
  82. 82. • Example #!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print " : ", print " : ", print " : ", else: print "No match!!" When the above code is executed, it produces following result − • : Cats are smarter than dogs • : Cats • : smarter
  83. 83. • The search Function This function searches for first occurrence of RE pattern within string with optional flags. • Here is the syntax for this function:, string, flags=0) Match Object Methods Description group(num=0) This method returns entire match (or specific subgroup num) groups() This method returns all matching subgroups in a tuple (empty if there weren't any)
  84. 84. #!/usr/bin/python import re line = "Cats are smarter than dogs"; searchObj = r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print " : ", print " : ", print " : ", else: print "Nothing found!!" When the above code is executed, it produces following result − • : Cats are smarter than dogs • : Cats • : smarter
  85. 85. • Search and Replace One of the most important re methods that use regular expressions is sub. Syntax re.sub(pattern, repl, string, max=0) • This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string.
  86. 86. #!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'D', "", phone) print "Phone Num : ", num When the above code is executed, it produces the following result − • Phone Num : 2004-959-559 • Phone Num : 2004959559
  87. 87. Database • Installing mysql in linux • In terminal=> #Sudo apt-get update #Sudo apt-get upgrade #Sudo apt-get install mysql-server #Sudo apt-get install python-mysqldb
  88. 88. Commands to get mysql prompt • The standard tool for interacting with MySQL is the mysql client program. To get started, issue the following command at your prompt: • Mysql –u root -p • You will be prompted to enter the root MySQL user's password. Enter the password you assigned when you installed MySQL, and you'll be presented with the MySQL monitor display:
  89. 89. • Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 41 Server version: 5.4.37-1 ubuntu 12. 4 L TS(Ubuntu) mysql>
  90. 90. • SQL is actually three separate sub-languages • ● DDL: Data Definition Language • – Used to create and maintain database structures • ● DCL: Data Control Language • – Used to specify who gets which access to what • ● DML: Data Manipulation Language • – Day-to-day query and update of the data model • – Probably about 99.9% of what we do with databases! • Data Control Language • GRANT SELECT, UPDATE (name, address) ON emp TO steve • ● This is almost exclusively used by the DBA • ● Not covered in the remainder of this tutorial
  91. 91. Create database and users • Let's create a database and assign a user to it. Issue the following commands at the MySQL prompt: • CREATE DATABASE testdb; • CREATE USER 'testuser'@localhost IDENTIFIED BY 'CHANGEME'; • GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@localhost; • exit
  92. 92. Create table • You can create and populate the example table with these statements: • mysql -u testuser -p Mysql>USE testdb; Mysql>CREATE TABLE shop (article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,dealer CHAR(20) DEFAULT '' NOT NULL,price DOUBLE(16,2) DEFAULT '0.00' NOT NULL, PRIMARY KEY(article, dealer));
  93. 93. Insert -select Mysql>INSERT INTO shop VALUES(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,' B',1.45),(3,'C',1.69),(3,'D',1.25),(4,'D',19.95); Mysql>SELECT * FROM shop;
  94. 94. Python DB API Designed to give Python programs access to RDBMS features using standard calls. Each compliant module interfaces to a particular RDBMS engine
  95. 95. Some Well-Known Database Modules Module Database MySQLdb MySQL cx_Oracle Oracle psycopg PostgreSQL psycopg2 PostgreSQL mxODBC Any RDBMS with ODBC drivers kinterbasdb Firebird/Interbase adodbapi Windows ADO data sources pydb2 DB/2
  96. 96. MySQLdb module • MySQLdb is a thin Python wrapper around mysql. It is compatible with the Python DB API, which makes the code more portable. Using this model is the preferred way of working with the MySQL. • Example
  97. 97. • mysql> create user 'testuser'@'localhost' • identified by 'xyz123'; • mysql> create database testdatabase; • mysql> grant all on *.* to 'testuser'@'localhost'; • mysql> use testdatabase; • mysql> create table student(Id INT PRIMARY KEY • AUTO_INCREMENT, Name VARCHAR(25)); • mysql> insert into student (name) values ('Tom'), • (‘Ren'), ('Harry');
  98. 98. Database fetch using fetchall() import MySQLdb as mdb import sys con=mdb.connect(‘localhost’,’usrname’,’xyz123’,’testdatabase’); if con: cur=con.cursor() cur.execute(“select * from student”) rows=cur.fetchall() for row in rows: print row
  99. 99. Exception in datbase Import MySQLdb as mdb Import sys Try: conn=mdb.connect(‘localhost’,’testuser’,’passwd’,’testdb’); cursor=conn.cursor() cursor.execute(“Delete from writers where id=5”) cursor.execute(“delete from writers where id=4”) conn.commit() Except mdb.Error, e: conn.rollback() print “Error %d: %s” %(e.args[0],e.args[1]) sys.exit(1) Cursor.close() Conn.close()