Python操作Mysql
最近在学习python,这种脚本语言毫无疑问的会跟数据库产生关联,因此这里介绍一下如何使用python操作mysql数据库。我python也是零基础学起,所以本篇博客针对的是python初学者,大牛可以选择绕道。
另外,本篇基于的环境是Ubuntu13.10,使用的python版本是2.7.5。
MYSQL数据库
MYSQL是一个全球领先的开源数据库管理系统。它是一个支持多用户、多线程的数据库管理系统,与Apache、PHP、Linux共同组成LAMP平台,在web应用中广泛使用,例如Wikipedia和YouTube。MYSQL包含两个版本:服务器系统和嵌入式系统。
环境配置
在我们开始语法学习之前,还需要按装mysql和python对mysql操作的模块。
安装mysql:
sudo apt-get install mysql-server
安装过程中会提示你输入root帐号的密码,符合密码规范即可。
接下来,需要安装python对mysql的操作模块:
sudo apt-get install python-mysqldb
这里需要注意:安装完python-mysqldb之后,我们默认安装了两个python操作模块,分别是支持C语言API的_mysql和支持Python API的MYSQLdb。稍后会重点讲解MYSQLdb模块的使用。
接下来,我们进入MYSQL,创建一个测试数据库叫testdb。创建命令为:
create database testdb;
然后,我们创建一个测试账户来操作这个testdb数据库,创建和授权命令如下:
create user 'testuser'@'127.0.0.1' identified by 'test123'; grant all privileges on testdb.* to 'testuser'@'127.0.0.1'; _mysql module
_mysql模块直接封装了MYSQL的C语言API函数,它与python标准的数据库API接口是不兼容的。我更推荐大家使用面向对象的MYSQLdb模块才操作mysql,这里只给出一个使用_mysql模块的例子,这个模块不是我们学习的重点,我们只需要了解有这个模块就好了。
#!/usr/bin/python # -*- coding: utf-8 -*- import _mysql import sys try: con = _mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb') con.query("SELECT VERSION()") result = con.use_result() print "MYSQL version : %s " % result.fetch_row()[0] except _mysql.Error, e: print "Error %d: %s %s" % (e.args[0], e.args[1]) sys.exit(1) finally: if con: con.close()
这个代码主要是获取当前mysql的版本,大家可以模拟敲一下这部分代码然后运行一下。
MYSQLdb module
MYSQLdb是在_mysql模块的基础上进一步进行封装,并且与python标准数据库API接口兼容,这使得代码更容易被移植。Python更推荐使用这个MYSQLdb模块来进行MYSQL操作。
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mysql try: conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb') cur = conn.cursor() cur.execute("SELECT VERSION()") version = cur.fetchone() print "Database version : %s" % version except mysql.Error, e: print "Error %d:%s" % (e.args[0], e.args[1]) exit(1) finally: if conn: conn.close()
我们导入了MySQLdb模块并把它重命名为mysql,然后调用MySQLdb模块的提供的API方法来操作数据库。同样也是获取当前主机的安装的mysql版本号。
创建新表
接下来,我们通过MySQLdb模块创建一个表,并在其中填充部分数据。实现代码如下:
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mysql conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb'); with conn: cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS writers"); cur.execute("CREATE TABLE writers(id INT PRIMARY KEY AUTO_INCREMENT, name varchar(25))") cur.execute("insert into writers(name) values('wangzhengyi')") cur.execute("insert into writers(name) values('bululu')") cur.execute("insert into writers(name) values('chenshan')")
这里使用了with语句。with语句会执行conn对象的enter()和__exit()方法,省去了自己写try/catch/finally了。
执行完成后,我们可以通过mysql-client客户端查看是否插入成功,查询语句:
select * from writers;
查询结果如下:
查询数据
刚才往表里插入了部分数据,接下来,我们从表中取出插入的数据,代码如下:
#!/usr/bin/python import MySQLdb as mysql conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb'); with conn: cursor = conn.cursor() cursor.execute("select * from writers") rows = cursor.fetchall() for row in rows: print row
查询结果如下:
(1L, 'wangzhengyi') (2L, 'bululu') (3L, 'chenshan')
dictionary cursor
我们刚才不论是创建数据库还是查询数据库,都用到了cursor。在MySQLdb模块有许多种cursor类型,默认的cursor是以元组的元组形式返回数据的。当我们使用dictionary cursor时,数据是以python字典形式返回的。这样我们就可以通过列名获取查询数据了。
还是刚才查询数据的代码,改为dictionary cursor只需要修改一行代码即可,如下所示:
#!/usr/bin/python import MySQLdb as mysql conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb'); with conn: cursor = conn.cursor(mysql.cursors.DictCursor) cursor.execute("select * from writers") rows = cursor.fetchall() for row in rows: print "id is %s, name is %s" % (row['id'], row['name'])
使用dictionary cursor,查询结果如下:
id is 1, name is wangzhengyi id is 2, name is bululu id is 3, name is chenshan
预编译
之前写过php的同学应该对预编译很了解,预编译可以帮助我们防止sql注入等web攻击还能帮助提高性能。当然,python肯定也是支持预编译的。预编译的实现也比较简单,就是用%等占位符来替换真正的变量。例如查询id为3的用户的信息,使用预编译的代码如下:
#!/usr/bin/python import MySQLdb as mysql conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb'); with conn: cursor = conn.cursor(mysql.cursors.DictCursor) cursor.execute("select * from writers where id = %s", "3") rows = cursor.fetchone() print "id is %d, name is %s" % (rows['id'], rows['name'])
我这里使用了一个%s的占位符来替换“3”,代表需要传入的是一个字符串类型。如果传入的不是string类型,则会运行报错。
事务
事务是指在一个或者多个数据库中对数据的原子操作。在一个事务中,所有的SQL语句的影响要不就全部提交到数据库,要不就全部都回滚。
对于支持事务机制的数据库,python接口在创建cursor的时候就开始了一个事务。可以通过cursor对象的commit()方法来提交所有的改动,也可以使用cursor对象的rollback方法来回滚所有的改动。
我这里写一个代码,对不存在的表进行插入操作,当抛出异常的时候,调用rollback进行回滚,实现代码如下:
#!/usr/bin/python # -*- coding: utf-8 -*- import MySQLdb as mysql try: conn = mysql.connect('127.0.0.1', 'testuser', 'test123', 'testdb'); cur = conn.cursor() cur.execute("insert into writers(name) values('wangzhengyi4')") cur.execute("insert into writers(name) values('bululu5')") cur.execute("insert into writerss(name) values('chenshan6')") conn.commit() except mysql.Error, e: if conn: conn.rollback() print "Error happens, rollback is call" finally: if conn: conn.close()
执行结果如下:
Error happens, rollback is call
因为前两条数据是正确的插入操作,但是因为整体回滚,所以数据库里也没有wangzhengyi4和bululu5这两个数据的存在。

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


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

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.