文章目录

  • 使用pymysql操作数据库
    • 01 - 基本操作步骤
    • 1-1 SQL查询
    • 1-2 SQL插入数据
      • 1-3 SQL修改数据
      • 1-4 SQL删除数据
    • 实例
      • I. 复制查询结果到其他数据库

使用pymysql操作数据库

01 - 基本操作步骤

#mermaid-svg-Hylt6wqKRwpTjFCo .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .label text{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .node rect,#mermaid-svg-Hylt6wqKRwpTjFCo .node circle,#mermaid-svg-Hylt6wqKRwpTjFCo .node ellipse,#mermaid-svg-Hylt6wqKRwpTjFCo .node polygon,#mermaid-svg-Hylt6wqKRwpTjFCo .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-Hylt6wqKRwpTjFCo .node .label{text-align:center;fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .node.clickable{cursor:pointer}#mermaid-svg-Hylt6wqKRwpTjFCo .arrowheadPath{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-Hylt6wqKRwpTjFCo .flowchart-link{stroke:#333;fill:none}#mermaid-svg-Hylt6wqKRwpTjFCo .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-Hylt6wqKRwpTjFCo .edgeLabel rect{opacity:0.9}#mermaid-svg-Hylt6wqKRwpTjFCo .edgeLabel span{color:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-Hylt6wqKRwpTjFCo .cluster text{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-Hylt6wqKRwpTjFCo .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-Hylt6wqKRwpTjFCo text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-Hylt6wqKRwpTjFCo .actor-line{stroke:grey}#mermaid-svg-Hylt6wqKRwpTjFCo .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-Hylt6wqKRwpTjFCo #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .sequenceNumber{fill:#fff}#mermaid-svg-Hylt6wqKRwpTjFCo #sequencenumber{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo #crosshead path{fill:#333;stroke:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .messageText{fill:#333;stroke:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-Hylt6wqKRwpTjFCo .labelText,#mermaid-svg-Hylt6wqKRwpTjFCo .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-Hylt6wqKRwpTjFCo .loopText,#mermaid-svg-Hylt6wqKRwpTjFCo .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-Hylt6wqKRwpTjFCo .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-Hylt6wqKRwpTjFCo .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-Hylt6wqKRwpTjFCo .noteText,#mermaid-svg-Hylt6wqKRwpTjFCo .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-Hylt6wqKRwpTjFCo .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-Hylt6wqKRwpTjFCo .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-Hylt6wqKRwpTjFCo .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-Hylt6wqKRwpTjFCo .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .section{stroke:none;opacity:0.2}#mermaid-svg-Hylt6wqKRwpTjFCo .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-Hylt6wqKRwpTjFCo .section2{fill:#fff400}#mermaid-svg-Hylt6wqKRwpTjFCo .section1,#mermaid-svg-Hylt6wqKRwpTjFCo .section3{fill:#fff;opacity:0.2}#mermaid-svg-Hylt6wqKRwpTjFCo .sectionTitle0{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .sectionTitle1{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .sectionTitle2{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .sectionTitle3{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-Hylt6wqKRwpTjFCo .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .grid path{stroke-width:0}#mermaid-svg-Hylt6wqKRwpTjFCo .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-Hylt6wqKRwpTjFCo .task{stroke-width:2}#mermaid-svg-Hylt6wqKRwpTjFCo .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .taskText:not([font-size]){font-size:11px}#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-Hylt6wqKRwpTjFCo .task.clickable{cursor:pointer}#mermaid-svg-Hylt6wqKRwpTjFCo .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-Hylt6wqKRwpTjFCo .taskText0,#mermaid-svg-Hylt6wqKRwpTjFCo .taskText1,#mermaid-svg-Hylt6wqKRwpTjFCo .taskText2,#mermaid-svg-Hylt6wqKRwpTjFCo .taskText3{fill:#fff}#mermaid-svg-Hylt6wqKRwpTjFCo .task0,#mermaid-svg-Hylt6wqKRwpTjFCo .task1,#mermaid-svg-Hylt6wqKRwpTjFCo .task2,#mermaid-svg-Hylt6wqKRwpTjFCo .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutside0,#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutside2{fill:#000}#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutside1,#mermaid-svg-Hylt6wqKRwpTjFCo .taskTextOutside3{fill:#000}#mermaid-svg-Hylt6wqKRwpTjFCo .active0,#mermaid-svg-Hylt6wqKRwpTjFCo .active1,#mermaid-svg-Hylt6wqKRwpTjFCo .active2,#mermaid-svg-Hylt6wqKRwpTjFCo .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-Hylt6wqKRwpTjFCo .activeText0,#mermaid-svg-Hylt6wqKRwpTjFCo .activeText1,#mermaid-svg-Hylt6wqKRwpTjFCo .activeText2,#mermaid-svg-Hylt6wqKRwpTjFCo .activeText3{fill:#000 !important}#mermaid-svg-Hylt6wqKRwpTjFCo .done0,#mermaid-svg-Hylt6wqKRwpTjFCo .done1,#mermaid-svg-Hylt6wqKRwpTjFCo .done2,#mermaid-svg-Hylt6wqKRwpTjFCo .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-Hylt6wqKRwpTjFCo .doneText0,#mermaid-svg-Hylt6wqKRwpTjFCo .doneText1,#mermaid-svg-Hylt6wqKRwpTjFCo .doneText2,#mermaid-svg-Hylt6wqKRwpTjFCo .doneText3{fill:#000 !important}#mermaid-svg-Hylt6wqKRwpTjFCo .crit0,#mermaid-svg-Hylt6wqKRwpTjFCo .crit1,#mermaid-svg-Hylt6wqKRwpTjFCo .crit2,#mermaid-svg-Hylt6wqKRwpTjFCo .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-Hylt6wqKRwpTjFCo .activeCrit0,#mermaid-svg-Hylt6wqKRwpTjFCo .activeCrit1,#mermaid-svg-Hylt6wqKRwpTjFCo .activeCrit2,#mermaid-svg-Hylt6wqKRwpTjFCo .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-Hylt6wqKRwpTjFCo .doneCrit0,#mermaid-svg-Hylt6wqKRwpTjFCo .doneCrit1,#mermaid-svg-Hylt6wqKRwpTjFCo .doneCrit2,#mermaid-svg-Hylt6wqKRwpTjFCo .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-Hylt6wqKRwpTjFCo .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-Hylt6wqKRwpTjFCo .milestoneText{font-style:italic}#mermaid-svg-Hylt6wqKRwpTjFCo .doneCritText0,#mermaid-svg-Hylt6wqKRwpTjFCo .doneCritText1,#mermaid-svg-Hylt6wqKRwpTjFCo .doneCritText2,#mermaid-svg-Hylt6wqKRwpTjFCo .doneCritText3{fill:#000 !important}#mermaid-svg-Hylt6wqKRwpTjFCo .activeCritText0,#mermaid-svg-Hylt6wqKRwpTjFCo .activeCritText1,#mermaid-svg-Hylt6wqKRwpTjFCo .activeCritText2,#mermaid-svg-Hylt6wqKRwpTjFCo .activeCritText3{fill:#000 !important}#mermaid-svg-Hylt6wqKRwpTjFCo .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-Hylt6wqKRwpTjFCo g.classGroup text .title{font-weight:bolder}#mermaid-svg-Hylt6wqKRwpTjFCo g.clickable{cursor:pointer}#mermaid-svg-Hylt6wqKRwpTjFCo g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-Hylt6wqKRwpTjFCo g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-Hylt6wqKRwpTjFCo .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-Hylt6wqKRwpTjFCo .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-Hylt6wqKRwpTjFCo .dashed-line{stroke-dasharray:3}#mermaid-svg-Hylt6wqKRwpTjFCo #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo .commit-id,#mermaid-svg-Hylt6wqKRwpTjFCo .commit-msg,#mermaid-svg-Hylt6wqKRwpTjFCo .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-Hylt6wqKRwpTjFCo g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-Hylt6wqKRwpTjFCo g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-Hylt6wqKRwpTjFCo g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-Hylt6wqKRwpTjFCo .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-Hylt6wqKRwpTjFCo .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-Hylt6wqKRwpTjFCo .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-Hylt6wqKRwpTjFCo .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-Hylt6wqKRwpTjFCo .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-Hylt6wqKRwpTjFCo .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-Hylt6wqKRwpTjFCo .edgeLabel text{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-Hylt6wqKRwpTjFCo .node circle.state-start{fill:black;stroke:black}#mermaid-svg-Hylt6wqKRwpTjFCo .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-Hylt6wqKRwpTjFCo #statediagram-barbEnd{fill:#9370db}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-state .divider{stroke:#9370db}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-Hylt6wqKRwpTjFCo .note-edge{stroke-dasharray:5}#mermaid-svg-Hylt6wqKRwpTjFCo .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-Hylt6wqKRwpTjFCo .error-icon{fill:#522}#mermaid-svg-Hylt6wqKRwpTjFCo .error-text{fill:#522;stroke:#522}#mermaid-svg-Hylt6wqKRwpTjFCo .edge-thickness-normal{stroke-width:2px}#mermaid-svg-Hylt6wqKRwpTjFCo .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-Hylt6wqKRwpTjFCo .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-Hylt6wqKRwpTjFCo .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-Hylt6wqKRwpTjFCo .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-Hylt6wqKRwpTjFCo .marker{fill:#333}#mermaid-svg-Hylt6wqKRwpTjFCo .marker.cross{stroke:#333}:root { --mermaid-font-family: "trebuchet ms", verdana, arial;}#mermaid-svg-Hylt6wqKRwpTjFCo {color: rgba(0, 0, 0, 0.75);font: ;}

建立数据库连接 *
创建cursor *
执行SQL语句 *
关闭cursor和连接 *
  1. 建立数据库连接
  2. 创建cursor
  3. 在cursor上执行SQL语句
  4. 关闭cursor和连接
import pymysql# 建立数据库连接
con = pymysql.connect(host = 'localhost',user = 'root',password = '9875321',database = 'world'
)# 创建cursor
cursor = con.cursor()
print(cursor)# ===============
# 执行SQL语句
# ===============# 关闭cursor
cursor.close()
# 关闭connection
con.close()

输出结果:

<pymysql.cursors.Cursor object at 0x000001C61B54E1F0>

1-1 SQL查询

# 在cursor上执行SQL语句## 1 - 查询
sql_select = '''select * from country limit 5;
'''
cursor.execute(sql_select)
## 使用fetchall()获取查询结果
data = cursor.fetchall() # 查询数据以复合tuple的形式存储
for item in data:print(item) # 每条查询数据为一个tuple

输出结果:

('ABW', 'Aruba', 'North America', 'Caribbean', 193.0, None, 103000, 78.4, 828.0, 793.0, 'Aruba', 'Nonmetropolitan Territory of The Netherlands', 'Beatrix', 129, 'AW')
('AFG', 'Afghanistan', 'Asia', 'Southern and Central Asia', 652090.0, 1919, 22720000, 45.9, 5976.0, None, 'Afganistan/Afqanestan', 'Islamic Emirate', 'Mohammad Omar', 1, 'AF')
('AGO', 'Angola', 'Africa', 'Central Africa', 1246700.0, 1975, 12878000, 38.3, 6648.0, 7984.0, 'Angola', 'Republic', 'José Eduardo dos Santos', 56, 'AO')
('AIA', 'Anguilla', 'North America', 'Caribbean', 96.0, None, 8000, 76.1, 63.2, None, 'Anguilla', 'Dependent Territory of the UK', 'Elisabeth II', 62, 'AI')
('ALB', 'Albania', 'Europe', 'Southern Europe', 28748.0, 1912, 3401200, 71.6, 3205.0, 2500.0, 'Shqipëria', 'Republic', 'Rexhep Mejdani', 34, 'AL')

1-2 SQL插入数据


sql_insert = '''insert into country values ('KLB', 'Klbania', 'Europe', 'Southern Europe', 28748.0, 1912, 3401200, 71.6, 3205.0, 2500.0, 'Shqipëria', 'Republic', 'Rexhep Mejdani', 34, 'AL');
'''
# 使用cursor执行sql语句
cursor.execute(sql_insert)

此时从本地数据库上查询无相关记录:

mysql> select * from country where `Code`='KLB';
Empty set (0.00 sec)

注意:只使用cursor执行插入语句,不会对本地数据库有所影响,需要使用con.commit()命令提交事务,此时插入数据的操作才能在本地数据库执行。完整脚本如下:

sql_insert = '''insert into country values ('KLB', 'Klbania', 'Europe', 'Southern Europe', 28748.0, 1912, 3401200, 71.6, 3205.0, 2500.0, 'Shqipëria', 'Republic', 'Rexhep Mejdani', 34, 'AL');
'''
cursor.execute(sql_insert)
try:con.commit()
except:print('Error')

回到本地数据库查询结果如下:

mysql> select * from country where `Code`='KLB';
+------+---------+-----------+-----------------+-------------+-----------+------------+----------------+---------+---------+------------+----------------+----------------+---------+-------+
| Code | Name    | Continent | Region          | SurfaceArea | IndepYear | Population | LifeExpectancy | GNP     | GNPOld  | LocalName  | GovernmentForm | HeadOfState    | Capital | Code2 |
+------+---------+-----------+-----------------+-------------+-----------+------------+----------------+---------+---------+------------+----------------+----------------+---------+-------+
| KLB  | Klbania | Europe    | Southern Europe |    28748.00 |      1912 |    3401200 |           71.6 | 3205.00 | 2500.00 | Shqip??ria | Republic       | Rexhep Mejdani |      34 | AL    |
+------+---------+-----------+-----------------+-------------+-----------+------------+----------------+---------+---------+------------+----------------+----------------+---------+-------+
1 row in set (0.00 sec)

1-3 SQL修改数据

下面要把国家代号为KLB的条目对应的Region字段修改为Antarctic,运行脚本前查询如下:

mysql> select region from country where `Code`='KLB';
+-----------------+
| region          |
+-----------------+
| Southern Europe |
+-----------------+
1 row in set (0.00 sec)

下面运行如下脚本:

sql_update = '''update country set Region='Antarctic' where Code='KLB';
'''
# 执行sql
cursor.execute(sql_update)# 提交事务
try:con.commit()
except:print('Error')

运行后再查询相关信息,region字段的值已经修改。

mysql> select region from country where `Code`='KLB';
+-----------+
| region    |
+-----------+
| Antarctic |
+-----------+
1 row in set (0.00 sec)

1-4 SQL删除数据

sql_delete = '''delete from country where Code='KLB';
'''
# 执行sql
cursor.execute(sql_delete)
# 提交事务
try:con.commit()
except:print('Error')

再查询本地数据库,相关数据信息已经删除:

mysql> select * from country where `Code`='KLB';
Empty set (0.00 sec)

实例

I. 复制查询结果到其他数据库

import pymysql# 第一步:建立数据库连接## 连接到原数据库
con = pymysql.connect(host = 'localhost',user = 'root',password = '9875321',database = 'world'
)
## 连接到目标数据库
con_target = pymysql.connect(host = 'localhost',user = 'root',password = '9875321',database = 'test'
)## 创建cursor
cursor = con.cursor()
cursor_target = con_target.cursor()#========================
# 第二步:查询相关信息## 查询原数据库的建表语句
sql_create_table = '''show create table country;
'''
cursor.execute(sql_create_table)
c = cursor.fetchone()
ct = c[1]
print(ct)## 查询数据
sql_querry = '''select * from country order by SurfaceArea desc limit 100;
'''
cursor.execute(sql_querry)
q = cursor.fetchall()#=======================
# 第三步:将信息复制到目标数据库## 在目标数据库中创建表格
check_sql = 'drop table if exists country;'### 在目标数据库cursor上执行建表SQL语句
cursor_target.execute(check_sql) # 避免重复创建产生错误
cursor_target.execute(ct+';')### 向目标数据库连接提交事务
try:con_target.commit()print('Table Created Successfully!')
except:print('Error')## 循环执行插入语句
for item in q:sql_insert = 'insert into country values%s;'% str(item)### 处理可能发生的SQL执行异常try:cursor_target.execute(sql_insert)except:print('InsertionError:' + sql_insert)## 执行完毕统一提交事务
try:con_target.commit()
except:print('Commission_Error')

脚本运行结果如下:

Table Created Successfully!
InsertionError:insert into country values('ATA', 'Antarctica', 'Antarctica', 'Antarctica', 13120000.0, None, 0, None, 0.0, None, '–', 'Co-administrated', '', None, 'AQ');
InsertionError:insert into country values('SDN', 'Sudan', 'Africa', 'Northern Africa', 2505813.0, 1956, 29490000, 56.6, 10162.0, None, 'As-Sudan', 'Islamic Republic', 'Omar Hassan Ahmad al-Bashir', 3225, 'SD');
InsertionError:insert into country values('GRL', 'Greenland', 'North America', 'North America', 2166090.0, None, 56000, 68.1, 0.0, None, 'Kalaallit Nunaat/Grønland', 'Part of Denmark', 'Margrethe II', 917, 'GL');
InsertionError:insert into country values('AFG', 'Afghanistan', 'Asia', 'Southern and Central Asia', 652090.0, 1919, 22720000, 45.9, 5976.0, None, 'Afganistan/Afqanestan', 'Islamic Emirate', 'Mohammad Omar', 1, 'AF');
InsertionError:insert into country values('SOM', 'Somalia', 'Africa', 'Eastern Africa', 637657.0, 1960, 10097000, 46.2, 935.0, None, 'Soomaaliya', 'Republic', 'Abdiqassim Salad Hassan', 3214, 'SO');
InsertionError:insert into country values('IRQ', 'Iraq', 'Asia', 'Middle East', 438317.0, 1932, 23115000, 66.5, 11500.0, None, 'Al-´Iraq', 'Republic', 'Saddam Hussein al-Takriti', 1365, 'IQ');
InsertionError:insert into country values('ESH', 'Western Sahara', 'Africa', 'Northern Africa', 266000.0, None, 293000, 49.8, 60.0, None, 'As-Sahrawiya', 'Occupied by Marocco', 'Mohammed Abdel Aziz', 2453, 'EH');
InsertionError:insert into country values('BLR', 'Belarus', 'Europe', 'Eastern Europe', 207600.0, 1991, 10236000, 68.0, 13714.0, None, 'Belarus', 'Republic', 'Aljaksandr Lukašenka', 3520, 'BY');
InsertionError:insert into country values('PRK', 'North Korea', 'Asia', 'Eastern Asia', 120538.0, 1948, 24039000, 70.7, 5332.0, None, 'Choson Minjujuui In´min Konghwaguk (Bukhan)', 'Socialistic Republic', 'Kim Jong-il', 2318, 'KP');

查询本地数据库如下:

mysql> use test;
Database changed
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| country        |
+----------------+
1 row in set (0.00 sec)mysql> select count(*) from country;
+----------+
| count(*) |
+----------+
|       91 |
+----------+
1 row in set (0.00 sec)

在数据库中显示数据小于100条,正好对应了SQL执行异常的数量。这里可以单独在数据库中执行相关语句:

mysql> insert into country values('ATA', 'Antarctica', 'Antarctica', 'Antarctica', 13120000.0, None, 0, None, 0.0, None, 'Â-', 'Co-administrated', '', None, 'AQ');
ERROR 1054 (42S22): Unknown column 'None' in 'field list'

结果显示,我们通过cursor.fetchall()创建SQL插入语句的时候,查询结果为null的值被自动替换为None,因此需要将插入语句部分的代码修改如下:


## 循环执行插入语句
for item in q:sql_insert = "insert into country values%s;"% str(item)sql_insert = sql_insert.replace("None","null") # 替换相关字符### 处理可能发生的SQL执行异常try:cursor_target.execute(sql_insert)except:print('InsertionError:' + sql_insert)

先将目标数据库内容还原为空,再运行修改后的脚本,可以得到如下结果:

mysql> select count(*) from country;
+----------+
| count(*) |
+----------+
|      100 |
+----------+
1 row in set (0.00 sec)

python学习笔记(1) - python操作mysql数据库【持续更新中...】相关推荐

  1. 【PHP+MySQL学习笔记】php操作MySQL数据库中语句

    我们常常用conn.php文件来建立与数据库的链接,然后在所需的文件中利用include 进行调用.这样有效防止对数据库属性的改动 而引起其他有关文件对数据调用的错误. 现在来看一个conn.php文 ...

  2. Python学习笔记编程小哥令狐~持续更新、、、

    Python学习笔记~编程小哥令狐 文章目录 Python学习笔记~编程小哥令狐 一.Python运行发生情况 二.变量 2.1变量引入前说明 2.2变量的命名和使用 2.3字符串 2.3.1使用方法 ...

  3. python学习笔记第十七天------------MySQL数据库

    文章目录 1. 数据库简介 1.1 RDBMS 1.2 SQL 1.3 MySQL 简介 2. 数据完整性 3. 数据库的指令 4. 数据表的指令 5. 增删改查(curd) 6. 数据库设计 7. ...

  4. golang 执行sql语句_Go语言学习笔记(Golang操作MySQL数据库)

    GO连接MySQL 通过GO页面作为客户端访问数据库 1.因为GO语言没有提供任何官方数据库驱动,所以需要安装第三方函数库. 2.由于在github上安装,所以需要安装git软件,安装过程一直点击下一 ...

  5. Python学习笔记之常用模块总结,持续更新...

    阅读目录 1. 时间模块--datetime 2. 文件目录操作模块--os 很多人学习python,不知道从何学起. 很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手. 很多已经 ...

  6. python学习--服务期间通讯和mysql数据库操作

    服务端 import socket import json s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) host='' port=1234 ...

  7. python连接数据库的技术_Python操作MySQL数据库的三种方法

    (1) 什么是MySQLdb? MySQLdb 是用于 Python 连接 MySQL 数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的. ...

  8. python使用pymysql包,操作mysql数据库,包括安装及使用(附代码)

    (本文书写的初衷,大家想简单是使用数据库,而不想深入了解时,可以直接使用) 1.安装 # Ubuntu20以上版本适用# 安装python包pip install pymysql# 安装数据库sudo ...

  9. python学习笔记:python类和对象,文件操作,网络编程

    目录 一.python面向对象 1.类和对象的定义 2.单继承 3.多继承 4.成员属性 5.异常 6.@property 二.python文件操作 文件的打开和读写 文件对象接口汇总 三.pytho ...

  10. #python学习笔记#使用python爬取网站数据并保存到数据库

    上篇说到如何使用python通过提取网页元素抓取网站数据并导出到excel中,今天就来说说如何通过获取json爬取数据并且保存到mysql数据库中. 本文主要涉及到三个知识点: 1.通过抓包工具获取网 ...

最新文章

  1. 关于.net core http error 502.5 - process failure
  2. Servlet基础之HttpServletResponse详解
  3. 剑指Offer_35_数组中的逆序对
  4. 当开启了延迟加载的开关,对象是怎么变成代理对象的?
  5. Java笔记-JSP初步研究
  6. eoLinker-AMS接口管理系统
  7. 技术小故事-Activity的Launch Mode引起的动画“疑案”
  8. 解决!Gallery中嵌套ListView,Gallery不能滑动的问题
  9. 小程序测试关注点之一-登录授权
  10. 关于影响NodeManager执行MR任务constainer数量的设置问题
  11. python关闭word_python自动化办公:玩转word之样式秘笈
  12. mysql5.7备份
  13. 计算机组成原理试题(三)(附参考答案)
  14. 克鲁伊夫:斗牛士因巴萨疯癫 红蓝一点克死皇马(2009-11-17)
  15. 【Linux】2. Linux实操命令
  16. 2022.10.10 英语背诵
  17. 微信公众号最新留言评论管理功能怎么开通获取?(内附留言功能开通视频链接)
  18. 【Unity3D 问题总结】Unity报错提示:Asset database transaction committed twice
  19. 172. 立体推箱子
  20. 【VB-01】离线语音模块,无需语音算法开发,直接嵌入式用。

热门文章

  1. Vue 倒计时插件 vue2-countdown
  2. MATLAB函数freqz的使用
  3. SmartSVN for Mac(SVN客户端)
  4. 电机控制park变换公式推导
  5. QTTabBar 1.5.4(Beta)版本
  6. Android怎么更换背景色,Android App更改背景颜色
  7. spss数据分析软件
  8. 使用selenium下载百度图片
  9. android 3d桌面壁纸,五款超酷安卓手机3D桌面软件合辑推荐
  10. SQL 基础教程:SQL 通配符