Python 实例
Python基础 2022-06-06 13:00:19小码哥的IT人生shichen
Python 实例
Python 语法
完整实例【打印 "Hello World"】:
print("Hello World!!! ")
完整实例【Python 中的注释】:
#This is a comment.
print("Hello, World!")
完整实例【文档字符串(Docstrings)】:
"""This is a
multiline docstring."""
print("Hello, World!")
Python 变量
完整实例【创建变量】:
x = 10
y = "Bill"
print(x)
print(y)
完整实例【同时输出文本和变量】:
x = "awesome"
print("Python is " + x)
完整实例【把变量添加到另一个变量】:
x = "Python is "
y = "awesome"
z = x + y
print(z)
Python 数字
完整实例【验证对象的类型】:
x = 10
y = 6.3
z = 2j
print(type(x))
print(type(y))
print(type(z))
完整实例【创建整数】:
x = 10
y = 37216654545182186317
z = -465167846
print(type(x))
print(type(y))
print(type(z))
完整实例【创建浮点数】:
x = 3.50
y = 2.0
z = -63.78
print(type(x))
print(type(y))
print(type(z))
完整实例【创建带有“e”的科学数字以表示 10 的幂】:
x = 27e4
y = 15E2
z = -49.8e100
print(type(x))
print(type(y))
print(type(z))
完整实例【创建复数】:
x = 2+3j
y = 7j
z = -7j
print(type(x))
print(type(y))
print(type(z))
Python Casting
完整实例【Casting - 整数】:
x = int(1)
y = int(2.5)
z = int("3")
print(x)
print(y)
print(z)
完整实例【Casting - 浮点】:
x = float(1)
y = float(2.5)
z = float("3")
w = float("4.6")
print(x)
print(y)
print(z)
print(w)
完整实例【Casting - 字符串】:
x = str("S2")
y = str(3)
z = str(4.0)
print(x)
print(y)
print(z)
Python 字符串
完整实例【获取字符串位置 1 处的字符】:
a = "Hello, World!"
print(a[1])
完整实例【子串。获取从位置 2 到位置 5 (不包括)的字符。】:
b = "Hello, World!"
print(b[2:5])
完整实例【删除字符串的开头或结尾的空格】:
a = " Hello, World! "
print(a.strip())
完整实例【返回字符串的长度】:
a = "Hello, World!"
print(len(a))
完整实例【把字符串转换为小写】:
a = "Hello, World!"
print(a.lower())
完整实例【把字符串转换为大写】:
a = "Hello, World!"
print(a.upper())
完整实例【把字符串替换为另一个字符串】:
a = "Hello, World!"
print(a.replace("World", "Kitty"))
完整实例【把字符串拆分为子串】:
a = "Hello, World!"
b = a.split(",")
print(b)
Python 运算符
完整实例【加运算符】:
x = 5
y = 3
print(x + y)
完整实例【减运算符】:
x = 5
y = 3
print(x - y)
完整实例【乘运算符】:
x = 5
y = 3
print(x * y)
完整实例【除运算符】:
x = 15
y = 3
print(x / y)
完整实例【取模运算符】:
x = 5
y = 2
print(x % y)
完整实例【赋值运算符】:
x = 5
print(x)
Python 列表
完整实例【创建列表】:
thislist = ["apple", "banana", "cherry"]
print(thislist)
完整实例【访问列表项】:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
完整实例【更改列表项目的值】:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "mango"
print(thislist)
完整实例【遍历列表】:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
完整实例【检查列表项是否存在】:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
完整实例【获取列表的长度】:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
完整实例【把一个项目添加到列表末端】:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
完整实例【把一个项目添加到指定索引】:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
完整实例【删除项目】:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
完整实例【删除最后一项】:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
完整实例【删除指定索引的项目】:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
完整实例【清空列表】:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
完整实例【使用 list() 构造函数来生成列表】:
thislist = list(("apple", "banana", "cherry"))
print(thislist)
Python 元组
完整实例【创建元组】:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
完整实例【访问元组项目】:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
完整实例【更改元组值】:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
完整实例【遍历元组】:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
完整实例【检查某个元组项目是否存在】:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
完整实例【获取元组的长度】:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
完整实例【删除元组】:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
完整实例【使用 tuple() 构造函数创建元组】:
thistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)
Python 集合
完整实例【创建集合】:
thisset = {"apple", "banana", "cherry"}
print(thisset)
# Note: the set list is unordered, meaning: the items will appear in a random order.
# Refresh this page to see the change in the result.
完整实例【遍历集合】:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
完整实例【检查项目是否存在】:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
完整实例【向集合添加一个项目】:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
完整实例【向集合添加多个项目】:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
完整实例【获取集合的长度】:
thisset = {"apple", "banana", "cherry"}
print(len(thisset))
完整实例【删除集合中的一个项目】:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
完整实例【使用 discard() 方法删除集合中的一个项目】:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
完整实例【使用 pop() 方法删除集合中的最后一项】:
thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x) #removed item
print(thisset) #the set after removal
完整实例【清空集合】:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
完整实例【删除集合】:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset) #this will raise an error because the set no longer exists
完整实例【使用 set() 构造函数创建集合】:
thisset = set(("apple", "banana", "cherry"))
print(thisset)
# Note: the set list is unordered, so the result will display the items in a random order.
Python 字典
完整实例【创建字典】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
print(thisdict)
完整实例【访问字典中的项目】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
x = thisdict["model"]
print(x)
完整实例【更改字典中某个具体项目的值】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
thisdict["year"] = 2019
print(thisdict)
完整实例【逐一打印字典中的所有键名】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
for x in thisdict:
print(x)
完整实例【逐一打印字典中的所有值】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
for x in thisdict:
print(thisdict[x])
完整实例【使用 values() 函数返回字典的值】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
for x in thisdict.values():
print(x)
完整实例【使用 items() 遍历键和值】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
for x, y in thisdict.items():
print(x, y)
完整实例【检查某个键是否存在】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
完整实例【获取字典的长度】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
完整实例【向字典添加一个项目】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
thisdict["color"] = "red"
print(thisdict)
完整实例【从字典删除一个项目】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
thisdict.pop("model")
print(thisdict)
完整实例【清空字典】:
thisdict = {
"brand": "Porsche",
"model": "911",
"year": 1963
}
thisdict.clear()
print(thisdict)
完整实例【使用 dict() 构造函数创建字典】:
thisdict = dict(brand="Porsche", model="911", year=1963)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Python If ... Else
完整实例【if 语句】:
a = 66
b = 200
if b > a:
print("b is greater than a")
完整实例【elif 语句】:
a = 66
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
完整实例【else 语句】:
a = 200
b = 66
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
完整实例【简写 if】:
a = 200
b = 66
if a > b: print("a is greater than b")
完整实例【简写 if ... else】:
a = 200
b = 66
print("A") if a > b else print("B")
完整实例【and 关键字】:
a = 200
b = 66
c = 500
if a > b and c > a:
print("Both conditions are True")
完整实例【or 关键字】:
a = 200
b = 66
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Python While 循环
完整实例【while 循环】:
i = 1
while i < 7:
print(i)
i += 1
完整实例【在 while 循环中使用 break 语句】:
i = 1
while i < 7:
print(i)
if i == 3:
break
i += 1
完整实例【在 while 循环中使用 continue 语句】:
i = 0
while i < 7:
i += 1
if i == 3:
continue
print(i)
Python For 循环
完整实例【for 循环】:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
完整实例【遍历字符串】:
for x in "banana":
print(x)
完整实例【在 for 循环中使用 break 语句】:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
完整实例【在 for 循环中使用 continue 语句】:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
完整实例【在 for 循环中使用 range() 函数】:
for x in range(10):
print(x)
完整实例【for 循环中的 Else】:
for x in range(10):
print(x)
else:
print("Finally finished!")
完整实例【嵌套 for 循环】:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Python 函数
完整实例【创建并调用函数】:
def my_function():
print("Hello from a function")
my_function()
完整实例【函数参数】:
def my_function(fname):
print(fname + " Gates")
my_function("Rory John")
my_function("Jennifer Katharine")
my_function("Phoebe Adele")
完整实例【默认参数值】:
def my_function(country = "China"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
完整实例【使函数返回值】:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
完整实例【递归】:
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Python Lambda
完整实例【将作为参数传递的数字加 10 的 lambda 函数】:
x = lambda a : a + 10
print(x(7))
完整实例【将参数 a 与参数 b 相乘的 lambda 函数】:
x = lambda a, b : a * b
print(x(2, 5))
完整实例【将参数 a、b 和 c 相加 lambda 函数】:
x = lambda a, b, c : a + b + c
print(x(6, 7, 2))
Python 数组
完整实例【创建数组】:
cars = ["Porsche", "Volvo", "BMW"]
print(cars)
完整实例【访问数组元素】:
cars = ["Porsche", "Volvo", "BMW"]
x = cars[0]
print(x)
完整实例【更改数组元素的值】:
cars = ["Porsche", "Volvo", "BMW"]
cars[0] = "Audi"
print(cars)
完整实例【获取数组的长度】:
cars = ["Porsche", "Volvo", "BMW"]
x = len(cars)
print(x)
完整实例【遍历数组中的所有元素】:
cars = ["Porsche", "Volvo", "BMW"]
for x in cars:
print(x)
完整实例【向数组添加元素】:
cars = ["Porsche", "Volvo", "BMW"]
cars.append("Audi")
print(cars)
完整实例【从数组删除元素】:
cars = ["Porsche", "Volvo", "BMW"]
cars.pop(1)
print(cars)
Python 类和对象
完整实例【创建类】:
class MyClass:
x = 7
print(MyClass)
完整实例【创建对象】:
class MyClass:
x = 7
p1 = MyClass()
print(p1.x)
完整实例【__init__() 函数】:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Bill", 63)
print(p1.name)
print(p1.age)
完整实例【创建对象方法】:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Bill", 63)
p1.myfunc()
完整实例【self 参数】:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("Bill", 63)
p1.myfunc()
完整实例【修改对象属性】:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Bill", 63)
p1.age = 64
print(p1.age)
完整实例【删除对象属性】:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Bill", 63)
del p1.age
print(p1.age)
完整实例【删除对象】:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("Bill", 63)
del p1
print(p1)
Python 迭代器
完整实例【从元组返回迭代器】:
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
完整实例【从字符串返回迭代器】:
mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
完整实例【遍历迭代器】:
mytuple = ("apple", "banana", "cherry")
for x in mytuple:
print(x)
完整实例【创建迭代器】:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
x = self.a
self.a += 1
return x
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
完整实例【停止迭代器】:
class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)
Python 模块
完整实例【使用模块】:
import mymodule
mymodule.greeting("Bill")
完整实例【模块中的变量】:
import mymodule
a = mymodule.person1["age"]
print(a)
完整实例【对模块重命名】:
import mymodule as mx
a = mx.person1["age"]
print(a)
完整实例【内置模块】:
import platform
x = platform.system()
print(x)
完整实例【使用 dir() 函数】:
import platform
x = dir(platform)
print(x)
完整实例【从模块导入】:
from mymodule import person1
print (person1["age"])
Python 日期
完整实例【导入 datetime 模块并显示当前日期】:
import datetime
x = datetime.datetime.now()
print(x)
完整实例【返回年份和 weekday 的名称】:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
完整实例【创建 date 对象】:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
完整实例【strftime() 方法】:
import datetime
x = datetime.datetime(2019, 10, 1)
print(x.strftime("%B"))
Python JSON
完整实例【把 JSON 转换为 Python】:
import json
# some JSON:
x = '{ "name":"Bill", "age":63, "city":"Seatle"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
完整实例【把 Python 转换为 JSON】:
import json
# a Python object (dict):
x = {
"name": "Bill",
"age": 63,
"city": "Seatle"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
完整实例【把 Python 对象转换为 JSON 字符串】:
import json
print(json.dumps({"name": "Bill", "age": 63}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
完整实例【转换包含所有合法数据类型的 Python 对象】:
import json
x = {
"name": "Bill",
"age": 63,
"married": True,
"divorced": False,
"children": ("Jennifer","Rory","Phoebe"),
"pets": None,
"cars": [
{"model": "Porsche", "mpg": 38.2},
{"model": "BMW M5", "mpg": 26.9}
]
}
print(json.dumps(x))
完整实例【使用 indent 参数来定义缩进量】:
import json
x = {
"name": "Bill",
"age": 63,
"married": True,
"divorced": False,
"children": ("Jennifer","Rory","Phoebe"),
"pets": None,
"cars": [
{"model": "Porsche", "mpg": 38.2},
{"model": "BMW M5", "mpg": 26.9}
]
}
# use four indents to make it easier to read the result:
print(json.dumps(x, indent=4))
完整实例【使用 separators 参数来更改默认分隔符】:
import json
x = {
"name": "Bill",
"age": 63,
"married": True,
"divorced": False,
"children": ("Jennifer","Rory","Phoebe"),
"pets": None,
"cars": [
{"model": "Porsche", "mpg": 38.2},
{"model": "BMW M5", "mpg": 26.9}
]
}
# use . and a space to separate objects, and a space, a = and a space to separate keys from their values:
print(json.dumps(x, indent=4, separators=(". ", " = ")))
完整实例【使用 sort_keys 参数指定结果是否应该排序】:
import json
x = {
"name": "Bill",
"age": 63,
"married": True,
"divorced": False,
"children": ("Jennifer","Rory","Phoebe"),
"pets": None,
"cars": [
{"model": "Porsche", "mpg": 38.2},
{"model": "BMW M5", "mpg": 26.9}
]
}
# sort the result alphabetically by keys:
print(json.dumps(x, indent=4, sort_keys=True))
Python RegEx
完整实例【检索字符串是否以 "China" 开头并以 "country" 结尾】:
import re
txt = "China is a great country"
x = re.search("^China.*country$", txt)
if (x):
print("YES! We have a match!")
else:
print("No match")
完整实例【使用 findall() 函数】:
import re
#Return a list containing every occurrence of "ai":
str = "China is a great country"
x = re.findall("a", str)
print(x)
完整实例【使用 search() 函数】:
import re
str = "China is a great country"
x = re.search("\s", str)
print("The first white-space character is located in position:", x.start())
完整实例【使用 split() 函数】:
import re
str = "China is a great country"
x = re.split("\s", str)
print(x)
完整实例【使用 sub() 函数】:
import re
str = "China is a great country"
x = re.sub("\s", "9", str)
print(x)
Python PIP
完整实例【使用包】:
import camelcase
c = camelcase.CamelCase()
txt = "hello world"
print(c.hump(txt))
Python Try Except
完整实例【当发生错误时,打印一条消息。】:
try:
print(x)
except:
print("An exception occurred")
完整实例【多个异常】:
#The try block will generate a NameError, because x is not defined:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
完整实例【使用 else 关键字定义没有出现错误时执行的代码块】:
#The try block does not raise any errors, so the else block is executed:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
完整实例【使用 finally 块执行代码,不论 try 块是否引发了错误】:
#The finally block gets executed no matter if the try block raises any errors or not:
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
Python 文件
完整实例【读取文件】:
f = open("demofile.txt", "r")
print(f.read())
完整实例【只读取文件的一部分】:
f = open("demofile.txt", "r")
print(f.read(5))
完整实例【读取文件中的一行】:
f = open("demofile.txt", "r")
print(f.readline())
完整实例【遍历文件的所有行,逐行读取整个文件】:
f = open("demofile.txt", "r")
for x in f:
print(x)
Python MySQL
完整实例【创建与数据库的连接】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)
print(mydb)
完整实例【在 MySQL 中创建数据库】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
#If this page is executed with no error, you have successfully created a database.
完整实例【检查数据库是否存在】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
完整实例【创建表】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
#If this page is executed with no error, you have successfully created a table named "customers".
完整实例【检查表是否存在】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
完整实例【在建表时创建主键】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
#If this page is executed with no error, the table "customers" now has a primary key
完整实例【在表格中插入记录】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
完整实例【插入多行】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
print(mycursor.rowcount, "record was inserted.")
完整实例【获取所插入的 ID】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("Michelle", "Blue Village")
mycursor.execute(sql, val)
mydb.commit()
print("1 record inserted, ID:", mycursor.lastrowid)
完整实例【选取表中的所有记录】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【选取表中的某些列】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT name, address FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【使用 fetchone() 方法读取表中的单行】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchone()
print(myresult)
完整实例【使用筛选器来选取】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = 'Park Lane 38'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【通配符】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address Like '%way%'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【防止 SQL 注入】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【按字母顺序对表的结果进行排序】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【按降序对结果进行排序(按字母顺序反向)】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers ORDER BY name DESC"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【从已有表中删除记录】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = 'Park Lane 38'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【防止 SQL 注入】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【删除已有的表】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE customers"
mycursor.execute(sql)
#If this page was executed with no error(s), you have successfully deleted the "customers" table.
完整实例【删除表,如果存在。】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "DROP TABLE IF EXISTS customers"
mycursor.execute(sql)
#If this page was executed with no error(s), you have successfully deleted the "customers" table.
完整实例【更新表中的已有记录】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
完整实例【防止 SQL 注入】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = %s WHERE address = %s"
val = ("Valley 345", "Canyon 123")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
完整实例【限制查询返回的记录数】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【根据两个或多个表之间的相关列合并行】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
INNER JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【左联接(LEFT JOIN)】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
LEFT JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
完整实例【右联接(RIGHT JOIN)】:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="myusername",
passwd="mypassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT \
users.name AS user, \
products.name AS favorite \
FROM users \
RIGHT JOIN products ON users.fav = products.id"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Python MongoDB
完整实例【创建数据库】:
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
# database created!
完整实例【检查数据库是否存在】:
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
print(myclient.list_database_names())
完整实例【创建集合】:
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
# collection created!
完整实例【检查集合是否存在】:
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
print(mydb.list_collection_names())
完整实例【插入集合】:
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
mydict = { "name": "John", "address": "Highway 37" }
x = mycol.insert_one(mydict)
print(x)
完整实例【返回 id 字段】:
import pymongo
myclient = pymongo.MongoClient('mongodb://localhost:27017/')
mydb = myclient['mydatabase']
mycol = mydb["customers"]
mydict = { "name": "Peter", "address": "Lowstreet 27" }
x = mycol.insert_one(mydict)
print(x.inserted_id)
完整实例【插入多个文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]
x = mycol.insert_many(mylist)
#print list of the _id values of the inserted documents:
print(x.inserted_ids)
完整实例【插入具有指定 ID 的多个文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
{ "_id": 1, "name": "John", "address": "Highway 37"},
{ "_id": 2, "name": "Peter", "address": "Lowstreet 27"},
{ "_id": 3, "name": "Amy", "address": "Apple st 652"},
{ "_id": 4, "name": "Hannah", "address": "Mountain 21"},
{ "_id": 5, "name": "Michael", "address": "Valley 345"},
{ "_id": 6, "name": "Sandy", "address": "Ocean blvd 2"},
{ "_id": 7, "name": "Betty", "address": "Green Grass 1"},
{ "_id": 8, "name": "Richard", "address": "Sky st 331"},
{ "_id": 9, "name": "Susan", "address": "One way 98"},
{ "_id": 10, "name": "Vicky", "address": "Yellow Garden 2"},
{ "_id": 11, "name": "Ben", "address": "Park Lane 38"},
{ "_id": 12, "name": "William", "address": "Central st 954"},
{ "_id": 13, "name": "Chuck", "address": "Main Road 989"},
{ "_id": 14, "name": "Viola", "address": "Sideway 1633"}
]
x = mycol.insert_many(mylist)
#print a list of the _id values of the inserted documents:
print(x.inserted_ids)
完整实例【查找集合中的首个文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x mycol.find_one()
print(x)
完整实例【查找集合中的所有文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
print(x)
完整实例【只查找某些字段】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }):
print(x)
完整实例【过滤结果】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Park Lane 38" }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
完整实例【高级查询】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
#address greater than S:
myquery = { "address": {"$gt": "S"} }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
完整实例【通过正则表达式来过滤】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
#address starts with S:
myquery = { "address": { "$regex": "^S" } }
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
完整实例【按字母顺序对结果排序】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name")
for x in mydoc:
print(x)
完整实例【按降序对结果排序(反向字母顺序)】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find().sort("name", -1)
for x in mydoc:
print(x)
完整实例【删除文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Mountain 21" }
mycol.delete_one(myquery)
#print the customers collection after the deletion:
for x in mycol.find():
print(x)
完整实例【删除多个文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": {"$regex": "^S"} }
x = mycol.delete_many(myquery)
print(x.deleted_count, "documents deleted")
完整实例【删除集合中的所有文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.delete_many({})
print(x.deleted_count, "documents deleted")
完整实例【删除集合】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.drop()
完整实例【更新文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } }
mycol.update_one(myquery, newvalues)
#print "customers" after the update:
for x in mycol.find():
print(x)
完整实例【更新多个/所有文档】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": { "$regex": "^S" } }
newvalues = { "$set": { "name": "Minnie" } }
x = mycol.update_many(myquery, newvalues)
print(x.modified_count, "documents updated.")
完整实例【限制结果】:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myresult = mycol.find().limit(5)
#print the result:
for x in myresult:
print(x)