search
HomeDatabaseMysql TutorialMySQL 事务预编译查询和Perl DBI简化_MySQL

MySQL 事务预编译查询和Perl DBI简化_MySQL

Jun 01, 2016 pm 02:03 PM
affairsimplementdatabasemethodInquiresimplifycompiletransfer

PerlMySQL查询

 

许多WEB应用程序内部通常重复运行带不同自变量的相同数据库查询,或以全有或全无块的形式执行一组相关查询。要满足这些要求,大多数数据库系统(包括MySQL)支持预编译查询与事务,多数脚本语言(如PHP和Perl)也拥有内置函数访问这些数据库特性。然而,上述两项特性是MySQL的新功能,因此给那些以前没有见过它们的开发者制造了一些麻烦。

本文旨在解决这一问题。文章讨论了支持MySQL事务和预编译查询的Perl DBI函数,并对其工作原理和应用方法进行说明。

 

预编译查询

在数据库中执行批量上传时,我们经常见到这样的SQL查询,这些查询仅在提交给INSERT命令的参数上有所不同。在这些情况下,应用所谓的预编译查询是一种常用的优化方法,它为查询建立一个模板,然后再向模板中导入不同的必要值,从而减少了数据库消耗。如果使用得当,这个特性能够显著提高应用程序的性能。

 

为说明这一点,我们以一个二域表格为例,如下面的列表A所示:

 

 

<ccid_code></ccid_code>mysql> SELECT * FROM users;

+-------+--------+

| fname | lname|

+----------------+

| Joe| Blow|

+-------+--------+

1 row in set (0.09 sec)

 

列表A

 

现在,假设我需要通过INSERT查询向这个表格中输入一组新记录。很明显,每次运行时,查询的格式保持不变,只有输入的值发生变化。要完成这一操作,最佳方法是为INSERT查询建立一个内置DBI“占位符”的模板,然后在每次运行时用实际值来代替占位符。如列表B所示:

 

<ccid_code></ccid_code>#!/usr/bin/perl

use DBI;

# create database connection

my $dbh = DBI->connect("DBI:mysql:database=somedb;
host=localhost", "user", "pass", {'RaiseError' => 1});

# prepare template query

my $sth = $dbh->prepare
("INSERT INTO users (fname, lname) VALUES (?, ?)");

# execute query with first set of parameters

$sth->execute('John', 'Doe');

# execute query with second set of parameters

$sth->execute('Jane', 'Low');

# close connection

$dbh->disconnect();

 

 

列表B

 

建立并执行一个带Perl DBI预编译SQL查询共分四个简单的步骤:

 

首先调用connect()方法初始化一个数据库句柄。这个方法以一个字符串为连接参数,这个字符串中包括数据库类型(”mysql”)、主机名称(”localhost”)和数据库名称(”somedb”);并向connect()方法提供用户名(”user”)和密码(”pass”)作为第二和第三自变量。

调用prepare()函数建立SQL查询模板。prepare()中用到的问号为代替实际值的占位符。

调用execute()方法向查询预编译模板中输入实际数据值,把它提交给占位符代替的自变量。注意,这里自变量的顺序十分重要,在上一步中必须为每个占位符定义一个自变量。每次通过一组不同的自变量调用execute()方法,就用相应的值执行一次INSERT查询。

调用disconnect()方法结束会话。

从一个外部文件中批量插入数据,是上述查询的典型应用。这时,首先调用prepare()方法,然后应用一个循环从文件中读入数据,每运行一次循环,即调用execute()方法在数据库中插入一组值。

 

事务

 

事务支持是MySQL的另外一项重要的新特性。简单来说,事务就是一个以全有或全无方式执行的SQL语句块(因为这些语句彼此相互依赖)。事务中的所有语句必须全部成功执行,事务才能成功完成;如果有任何一个语句出现错误,系统就会“退回”到原始状态,以避免数据连接/破坏问题。

 

在两个银行账户间转账就是一个典型的例子。在数据库中,转账过程包括二个步骤:首先,从源账户余额中提取转账金额,然后将其存入目标账户的余额中。如果第二步发生错误,那么第一步必须倒退到一个前面的“快照”,以避免余额失衡。大部分数据库(包括MySQL)通过一组命令完成这种转账过程。

 

START TRANSACTION命令标记一个新事务块开始,接着执行一系列SQL命令。

COMMIT命令标记一个事务块结束,表示在事务中发生的所有变化应被“提交”或永久化。

ROLLBACK命令标记一个事务块结束,并表示事务中发生的所有变化必须被撤销。

为说明它的实际应用,我们以一个存储用户账户的表格为例,如列表C所示:

 

<ccid_code></ccid_code>mysql> SELECT * FROM accounts;

+----+------------+---------+

| id | label| balance |

+----+------------+---------+

|1 | Savings #1 |1000 |

|2 | Current #1 |2000 |

|3 | Current #2 |3000 |

+----+------------+---------+

3 rows in set (0.34 sec)

 

列表C

现在,假设我要转账400美元。实际的“事务”通过两个UPDATE语句来执行,一个语句将转账金额从源账户中取出,另一语句将其存入目标账户。如果我只是在账户间进行转账,那么整个过程中,所有账户的总余额(00)应一直保持不变。以下是完成转账的DBI代码(列表D):

 

 

<ccid_code></ccid_code>#!/usr/bin/perl

use DBI;

# create database connection

my $dbh = DBI->connect
("DBI:mysql:database=somedb;host=localhost", 
"user", "pass", {'RaiseError' => 1, 'AutoCommit' => 0});

# trap errors using eval{}

eval {

# debit account #1

$dbh->do("UPDATE accounts SET balance = balance-400 WHERE id=1");

# credit account #2

$dbh->do("UPDATE accounts SET balance = balance+400 WHERE id=2");

# no errors so far

# commit changes

$dbh->commit();

};

# any errors

# rollback

if ($@) {

print "Transaction aborted: $@";

$dbh->rollback();

}

# close connection

$dbh->disconnect();

 

列表D

 

在Perl中执行一个事务共有四个基本步骤:

 

第一步,关闭数据库“自动提交”。(本质上说,自动提交意味着系统保存你所做的变化。)这一步很重要,因为你只应在确定所有的事务“单元”成功完成后,才保存发生的变化。在上面的例子中,我们在调用connect()方法时将AutoCommit选项设为0,完成关闭操作。

下一步,以普通方式执行INSERT、UPDATE和/或DELETE查询,但将这些查询包含在一个eval{}块中。这样做是为了保证:如果发生错误,程序会在块以外中断,事务就不会被提交。如果一切正常,发生的变化将在事务块中的所有查询执行后,通过调用commit()提交给数据库。

如果在执行事务块中任何一个语句时出现错误,程序将在eval{}块外中断,并继续执行后面的代码。这些代码首先打印一段错误信息,然后通过rollback()函数将数据库退回到事务前的状态。注意,一旦调用这个函数,事务即无法逆转。

调用disconnect()方法结束会话。

如你所见,用Perl和MySQL执行事务模型能够使MySQL数据库在遇到查询执行错误时更加稳定。但是,在新开始着手用这些新特性重写代码前,必须注意,它们实际上增加了系统的性能消耗;因此,在执行它们之前,最好进行一下成本效益分析。

Statement
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
MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

Is MySQL Beginner-Friendly? Assessing the Learning CurveIs MySQL Beginner-Friendly? Assessing the Learning CurveApr 17, 2025 am 12:19 AM

MySQL is suitable for beginners because: 1) easy to install and configure, 2) rich learning resources, 3) intuitive SQL syntax, 4) powerful tool support. Nevertheless, beginners need to overcome challenges such as database design, query optimization, security management, and data backup.

Is SQL a Programming Language? Clarifying the TerminologyIs SQL a Programming Language? Clarifying the TerminologyApr 17, 2025 am 12:17 AM

Yes,SQLisaprogramminglanguagespecializedfordatamanagement.1)It'sdeclarative,focusingonwhattoachieveratherthanhow.2)SQLisessentialforquerying,inserting,updating,anddeletingdatainrelationaldatabases.3)Whileuser-friendly,itrequiresoptimizationtoavoidper

Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Explain the ACID properties (Atomicity, Consistency, Isolation, Durability).Apr 16, 2025 am 12:20 AM

ACID attributes include atomicity, consistency, isolation and durability, and are the cornerstone of database design. 1. Atomicity ensures that the transaction is either completely successful or completely failed. 2. Consistency ensures that the database remains consistent before and after a transaction. 3. Isolation ensures that transactions do not interfere with each other. 4. Persistence ensures that data is permanently saved after transaction submission.

MySQL: Database Management System vs. Programming LanguageMySQL: Database Management System vs. Programming LanguageApr 16, 2025 am 12:19 AM

MySQL is not only a database management system (DBMS) but also closely related to programming languages. 1) As a DBMS, MySQL is used to store, organize and retrieve data, and optimizing indexes can improve query performance. 2) Combining SQL with programming languages, embedded in Python, using ORM tools such as SQLAlchemy can simplify operations. 3) Performance optimization includes indexing, querying, caching, library and table division and transaction management.

MySQL: Managing Data with SQL CommandsMySQL: Managing Data with SQL CommandsApr 16, 2025 am 12:19 AM

MySQL uses SQL commands to manage data. 1. Basic commands include SELECT, INSERT, UPDATE and DELETE. 2. Advanced usage involves JOIN, subquery and aggregate functions. 3. Common errors include syntax, logic and performance issues. 4. Optimization tips include using indexes, avoiding SELECT* and using LIMIT.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

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),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment