快速熟悉python 下使用mysql(MySQLdb)
python
首先你需要安装上mysql和MySQLdb模块(当然还有其他模块可以用),这里我就略过了,如果遇到问题自行百度(或者评论在下面我可以帮忙看看)
这里简单记录一下自己使用的学习过程:
一、连接数据库
MySQLdb提供了connect函数,使用如下
cxn=MySQLdb.Connect(host='localhost',user='root',passwd='',db='samp_db',port=3306)
这里的参数的意义都是很明确的,但是这些参数并不是都是必须的:
1、host参数表示的是数据库所在地址,默认值是localhost,也就是说本机运行这个参数可以不指定
2、user、passwd 数据库的用户名和密码,必须存在
3、db 选择你要操作的数据库名,这个可以稍后指定,非必须
4、port 端口号,默认值3306
5、charset 用来指定字符集(默认utf8)
二、操作数据库
1、某些对象可以直接使用query(但是不推荐使用(所以这里基本略过),即使是使用也一定要先判断是否存在这个属性)
cxn.query('sql语句')
2、使用cur
cur=cxn.cursor()
这样我们就能使用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
这段代码就能返回表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')
这样我们会可以看待结果:
(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'))
看似是一摸一样的完成了这项工作,但是这时候我们用终端连上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()
三、获取返回值
上面我们是将查询的结果都存在了一个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()
上面用到了两处参数,第五行和第12行
另外当执行多个命令要用executemany(op,args)它类似 execute() 和 map() 的结合, 为给定的每一个参数准备并执行一个数据库查询/命令
五、零碎
上面说过db这个属性可以在连接之后指定,如下:
cxn.select_db('students')

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

Convert XML to PDF with high quality on your mobile phone requires: parsing XML in the cloud and generating PDFs using a serverless computing platform. Choose efficient XML parser and PDF generation library. Handle errors correctly. Make full use of cloud computing power to avoid heavy tasks on your phone. Adjust complexity according to requirements, including processing complex XML structures, generating multi-page PDFs, and adding images. Print log information to help debug. Optimize performance, select efficient parsers and PDF libraries, and may use asynchronous programming or preprocessing XML data. Ensure good code quality and maintainability.

Converting XML to PDF directly on Android phones cannot be achieved through the built-in features. You need to save the country through the following steps: convert XML data to formats recognized by the PDF generator (such as text or HTML); convert HTML to PDF using HTML generation libraries such as Flying Saucer.
