Python数据库的连接实现方法与注意事项
在Python中要连接数据库,首先我们得先安装几个重要的东西,主要有:
(1)Python-dev包
(2)setuptools-0.6c11.tar.gz
(3)MySQL-python-1.2.3.tar.gz
下面分别来说说这三个主要的包的安装步骤:
(1)Python-dev包
直接yum install python-devel
(2)setuptools-0.6c11.tar.gz
在网上下载后,先解压:tar zxf setuptools-0.6c11.tar.gz,完毕后cd到解压后的文件夹,执行:
python setup.py build
python setup.py install
(3)MySQL-python-1.2.3.tar.gz
跟安装setuptools-0.6c11.tar.gz步骤一样,先解压:tar zxfMySQL-python-1.2.3.tar.gz,
完毕后cd到解压后的文件夹,执行:
python setup.py build
python setup.py install
在执行上述命令之前,最好先修改一个文件,我们先查找mysql_config的位置,使用命令:
find / -name mysql_config
然后我们获取到它的路径,我的是:/usr/bin/mysql_config,然后修改MySQL-python-1.2.3目录下
的site.cfg文件,去掉mysql_config=XXX这行前面的#,改为:
mysql_config = /usr/bin/mysql_config
经过上面的步骤,我们基本就可以MySQLdb安装好了。
可以测试一下,在Python的交互式命令行,输入import MySQLdb,如果没有报错,就说明已经安装好。
下面的Python代码展示了如何连接数据库,并执行数据库的一些操作:
import MySQLdb try: conn = MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306) cur = conn.cursor() cur.execute('create database if not exists PythonDB') conn.select_db('PythonDB') cur.execute('create table Test(id int,name varchar(20),info varchar(20))') value = [1,'ACdreamer','student'] cur.execute('insert into Test values(%s,%s,%s)',value) values = [] for i in range(20): values.append((i,'Hello World!','My number is '+str(i))) cur.executemany('insert into Test values(%s,%s,%s)',values) cur.execute('update Test set name="ACdreamer" where id=3') conn.commit() cur.close() conn.close() except MySQLdb.Error,msg: print "MySQL Error %d: %s" %(msg.args[0],msg.args[1])
可以看出,连接数据库大致分为以下步骤:
(1)建立和数据库系统的连接
(2)获取操作游标
(3)执行SQL,创建一个数据库(当然这一步不是必需的,因为我们可以用已经存在的数据库)
(4)选择数据库
(5)进行各种数据库操作
(6)操作完毕后,提交事务(这一步很重要,因为只有提交事务后,数据才能真正写进数据库)
(7)关闭操作游标
(8)关闭数据库连接
当然,如果我们使用已经存在的数据库,那么在获取连接时就可以制定了,比如:
conn = MySQLdb.connect(host='localhost', user='root', passwd='root', db='PythonDB')
如果数据库中有中文,为了防止乱码,我们加入属性charset = 'uft-8'或者'gb2312',charset要跟数据库的编码一致。
conn = MySQLdb.connect(host='localhost', user='root',
passwd='root', db='PythonDB',charset='utf8')
下面贴一下常用的函数:
数据库连接对事务操作的方法:commit() 提交 rollback() 回滚
cursor用来执行命令的方法:
callproc(self,procname,args)
用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数
execute(self, query, args)
执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数
executemany(self, query, args)
执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数
nextset(self)
移动到下一个结果集
cursor用来接收返回值的方法:
fetchall(self)
接收全部的返回结果行
fetchmany(self, size=None)
接收size条返回结果行.如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据
fetchone(self)
返回一条结果行
scroll(self, value, mode='relative')
移动指针到某一行,如果mode='relative',则表示从当前所在行移动value条,如果 mode='absolute',则表示从结果集的第一行移动value条。

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

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

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

Go language is an efficient, concise and easy-to-learn programming language. It is favored by developers because of its advantages in concurrent programming and network programming. In actual development, database operations are an indispensable part. This article will introduce how to use Go language to implement database addition, deletion, modification and query operations. In Go language, we usually use third-party libraries to operate databases, such as commonly used sql packages, gorm, etc. Here we take the sql package as an example to introduce how to implement the addition, deletion, modification and query operations of the database. Assume we are using a MySQL database.

Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

Hibernate polymorphic mapping can map inherited classes to the database and provides the following mapping types: joined-subclass: Create a separate table for the subclass, including all columns of the parent class. table-per-class: Create a separate table for subclasses, containing only subclass-specific columns. union-subclass: similar to joined-subclass, but the parent class table unions all subclass columns.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

HTML cannot read the database directly, but it can be achieved through JavaScript and AJAX. The steps include establishing a database connection, sending a query, processing the response, and updating the page. This article provides a practical example of using JavaScript, AJAX and PHP to read data from a MySQL database, showing how to dynamically display query results in an HTML page. This example uses XMLHttpRequest to establish a database connection, send a query and process the response, thereby filling data into page elements and realizing the function of HTML reading the database.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.
