Home Database Mysql Tutorial 快速熟悉python 下使用mysql(MySQLdb)

快速熟悉python 下使用mysql(MySQLdb)

Jun 01, 2016 pm 01:13 PM
mysql python Baidu Connect to the database

python

首先你需要安装上mysql和MySQLdb模块(当然还有其他模块可以用),这里我就略过了,如果遇到问题自行百度(或者评论在下面我可以帮忙看看)

这里简单记录一下自己使用的学习过程:

一、连接数据库

MySQLdb提供了connect函数,使用如下

  cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
Copy after login

  这里的参数的意义都是很明确的,但是这些参数并不是都是必须的:

1、host参数表示的是数据库所在地址,默认值是localhost,也就是说本机运行这个参数可以不指定

2、user、passwd 数据库的用户名和密码,必须存在

3、db 选择你要操作的数据库名,这个可以稍后指定,非必须

4、port 端口号,默认值3306

5、charset 用来指定字符集(默认utf8)

二、操作数据库

1、某些对象可以直接使用query(但是不推荐使用(所以这里基本略过),即使是使用也一定要先判断是否存在这个属性)

  cxn.query('sql语句')
Copy after login

2、使用cur

  cur=cxn.cursor()
Copy after login

这样我们就能使用cur执行各种操作了,示例代码如下:

1 import MySQLdb2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)3 cur=cxn.cursor()4 result=cur.execute('select * from students')5 for i in cur.fetchall():6 print i
Copy after login

这段代码就能返回表students中的所有信息了,也就是你进入mysql输入select * from students之后所显示的内容。这里我就假设大家都了解sql的语句 使用了(不了解的可以去学或者用ORM操作数据库)

接下来我们演示一下怎么更新表,以怎么向表中插入数据为例:

 1 import MySQLdb 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306) 3 cur=cxn.cursor() 4 def showtables(tname): 5 result=cur.execute('select * from %s'%tname) 6 for i in cur.fetchall(): 7 print i 8 showtables('students') 9 cur.execute("insert into students values(4,'liu4',100)")10 print 'after insert'11 showtables('students')
Copy after login

这样我们会可以看待结果:

(1L, 'liu', Decimal('100'))(2L, 'liu2', Decimal('90'))(3L, 'liu3', Decimal('98'))after insert(1L, 'liu', Decimal('100'))(2L, 'liu2', Decimal('90'))(3L, 'liu3', Decimal('98'))(4L, 'liu4', Decimal('100'))
Copy after login

看似是一摸一样的完成了这项工作,但是这时候我们用终端连上mysql。执行一条select * from students却发现我们插入的那条并没有进去。这是因为 我们还缺少一个commit工作。另外工作完成之后我们需要关闭与数据库的连接,于是更改代码如下

 1 import MySQLdb 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306) 3 cur=cxn.cursor() 4 def showtables(tname): 5 result=cur.execute('select * from %s'%tname) 6 for i in cur.fetchall(): 7 print i 8 showtables('students') 9 cur.execute("insert into students values(4,'liu4',100)")10 cxn.commit()11 print 'after insert'12 showtables('students')13 cur.close()14 cxn.close()
Copy after login

三、获取返回值

上面我们是将查询的结果都存在了一个result变量里的,比呢切返回的都是tuple。但是cursor还有若干方法:来接收返回值

fetchall(self):接收全部的返回结果行.
fetchmany(self, size=None):接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据.
fetchone(self):返回一条结果行.
scroll(self, value, mode='relative'):移动指针到某一行.如果mode='relative',则表示从当前所在行移动value条,如果mode='absolute',则表示从结果集的 第一行移动value条.

四、批量执行和参数

使用MySQLdb我们不仅可以执行一条语句,更可以将他与python结合起来,这样我们就可以批量操做了

 1 import MySQLdb 2 cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306) 3 cur=cxn.cursor() 4 def showtables(tname): 5 result=cur.execute('select * from %s'%tname) 6 for i in cur.fetchall(): 7 print i 8 showtables('students') 9 v=[]10 for i in range(10):11 v.append((i,'liu'+str(i),98))12 cur.executemany("insert into students values(%s,%s,%s)",v)13 cxn.commit()14 print 'after insert'15 showtables('students')16 cur.close()17 cxn.close()
Copy after login

上面用到了两处参数,第五行和第12行

另外当执行多个命令要用executemany(op,args)它类似 execute() 和 map() 的结合, 为给定的每一个参数准备并执行一个数据库查询/命令

五、零碎

上面说过db这个属性可以在连接之后指定,如下:

cxn.select_db('students')
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

Binance Trading App Official Website Download Portal Binance Trading App Official Website Binance Trading App Official Website Download Portal Binance Trading App Official Website Apr 24, 2025 pm 02:18 PM

To safely access the Binance official platform and download the APP, you can use the following steps: 1) Use a trusted search engine to search for "Binance" and check the domain name; 2) View the official social media to obtain the URL; 3) Consult the official customer service to confirm the URL; 4) Use a trusted navigation website. The steps to download the APP include: 1) Visit Binance official website; 2) Find the APP download portal; 3) Select the download method (scan the QR code, download the app store, and directly download the APK file).

SQL vs. MySQL: Clarifying the Relationship Between the Two SQL vs. MySQL: Clarifying the Relationship Between the Two Apr 24, 2025 am 12:02 AM

SQL is a standard language for managing relational databases, while MySQL is a database management system that uses SQL. SQL defines ways to interact with a database, including CRUD operations, while MySQL implements the SQL standard and provides additional features such as stored procedures and triggers.

MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Binance download link Binance download path Binance download link Binance download path Apr 24, 2025 pm 02:12 PM

To safely download the Binance APP, you need to go through the official channels: 1. Visit the Binance official website, 2. Find and click the APP download portal, 3. Choose to scan the QR code, app store, or directly download the APK file to download to ensure that the link and developer information are authentic, and enable two-factor verification to protect the security of the account.

See all articles