Table of Contents
数据库技术-JDBC中的PreparedStatement和Transaction
Transaction
Home Database Mysql Tutorial 数据库技术-JDBC中的PreparedStatement和Transaction

数据库技术-JDBC中的PreparedStatement和Transaction

Jun 07, 2016 pm 03:23 PM
technology database

数据库技术-JDBC中的PreparedStatement和Transaction PreparedStatement 首先介绍PreparedStatement: 1、PreparedStatement是一种Statement 2、比父接口提供了更多可以让我们用的方式. prepstmt = conn.prepareStatement(INSERT INTO animal VALUES(?,?,?))

数据库技术-JDBC中的PreparedStatement和Transaction

PreparedStatement
首先介绍PreparedStatement: 1、PreparedStatement是一种Statement 2、比父接口提供了更多可以让我们用的方式. prepstmt = conn.prepareStatement("INSERT INTO animal VALUES(?,?,?)"); prepstmt.setInt(1, 1);
prepstmt.setString(2, "pig");
prepstmt.setInt(3, 10);
prepstmt.execute();
三个? 表示三个占位符,设定三个位置的值。 1表示第一个问号的值,2表示第二个问号的值,3表示第三个问号的值。
可以这样理解: 我首先准备好一条sql语句,这条语句中有三个值等待确定,接下来依次确定三个值的类型和值。
package myjdbc;

import java.sql.*;

public class PreparedJdbc {
	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3308/zoo";
	private static String user = "root";
	private static String password = "123";
	private static Connection conn = null;
	private static PreparedStatement prepstmt = null;
	private static ResultSet rs = null;

	public static void main(String[] args) {
		try {
			Class.forName(driver);
			//
			conn = DriverManager.getConnection(url,user,password);
			prepstmt = conn
					.prepareStatement("INSERT INTO animal VALUES(?,?,?)");
			prepstmt.setInt(1, 1);
			prepstmt.setString(2, "pig");
			prepstmt.setInt(3, 10);
			prepstmt.execute();
			System.out.println("finish!");
			
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();

		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (prepstmt != null) {
					prepstmt.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
}
Copy after login

MySQL: \

Transaction

先举个简单的例子,A账户转账到B账户,一般需要两条sql语句,一条update A账户上的钱,一条update B账户的钱。这两天update语句必须同时执行成功,或者同时不执行成功,不予许出现中间情况,一条成功一条不成功。

这两条语句就构成了transaction。

conn.setAutoCommit(false);//首先设置自动提交false
stmt = conn.createStatement();
stmt.addBatch("insert into animal values (51, '500', 3)");
stmt.addBatch("insert into animal values (52, '500', 4)");
stmt.addBatch("insert into animal values (53, '500', 5)");
stmt.executeBatch();//三条语句批处理
conn.commit();
conn.setAutoCommit(true);//还原默认自动提交true

设置回滚

catch (SQLException e) {
e.printStackTrace();
try {
if (conn != null) {
conn.rollback();
conn.setAutoCommit(true);
}
}

下面代码:

package myjdbc;

import java.sql.*;

public class TestTransaction {

	public static void main(String[] args) {

		Connection conn = null;
		Statement stmt = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(
					"jdbc:mysql://localhost:3308/zoo", "root", "123");

			conn.setAutoCommit(false);
			stmt = conn.createStatement();
			stmt.addBatch("insert into animal values (51, '500', 3)");
			stmt.addBatch("insert into animal values (52, '500', 4)");
			stmt.addBatch("insert into animal values (53, '500', 5)");
			stmt.executeBatch();
			conn.commit();
			conn.setAutoCommit(true);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();

			try {
				if (conn != null) {
					conn.rollback();
					conn.setAutoCommit(true);
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (stmt != null)
					stmt.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

} 
Copy after login

Mysql:

\

Words in the end

在JDBC应用中,如果你已经是稍有水平开发者,你就应该始终以PreparedStatement代替Statement.也就是说,在任何时候都不要使用Statement.
基于以下的原因:
一.代码的可读性和可维护性.
虽然用PreparedStatement来代替Statement会使代码多出几行,但这样的代码无论从可读性还是可维护性上来说.都比直接用Statement的代码高很多档次:

stmt.executeUpdate("insert into tb_name (col1,col2,col2,col4) values ('"+var1+"','"+var2+"',"+var3+",'"+var4+"')");

perstmt = con.prepareStatement("insert into tb_name (col1,col2,col2,col4) values (?,?,?,?)");
perstmt.setString(1,var1);
perstmt.setString(2,var2);
perstmt.setString(3,var3);
perstmt.setString(4,var4);
perstmt.executeUpdate();

二.PreparedStatement尽最大可能提高性能.
每一种数据库都会尽最大努力对预编译语句提供最大的性能优化.因为预编译语句有可能被重复调用.所以语句在被DB的编译器编译后的执行代码被缓存下来,那么下次调用时只要是相同的预编译语句就不需要编译,只要将参数直接传入编译过的语句执行代码中(相当于一个涵数)就会得到执行.这并不是说只有一个Connection中多次执行的预编译语句被缓存,而是对于整个DB中,只要预编译的语句语法和缓存中匹配.那么在任何时候就可以不需要再次编译而可以直接执行.而statement的语句中,即使是相同一操作,而由于每次操作的数据不同所以使整个语句相匹配的机会极小,几乎不太可能匹配.比如:
insert into tb_name (col1,col2) values ('11','22');
insert into tb_name (col1,col2) values ('11','23');
即使是相同操作但因为数据内容不一样,所以整个个语句本身不能匹配,没有缓存语句的意义.事实是没有数据库会对普通语句编译后的执行代码缓存.

三.极大地提高了安全性.
 

Transaction 用在需要同步数据时非常重要,确保在几条批处理语句的同时执行成功。

2014.1.9

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

How does Hibernate implement polymorphic mapping? How does Hibernate implement polymorphic mapping? Apr 17, 2024 pm 12:09 PM

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.

iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos iOS 18 adds a new 'Recovered' album function to retrieve lost or damaged photos Jul 18, 2024 am 05:48 AM

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

Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Review! Deep model fusion (LLM/basic model/federated learning/fine-tuning, etc.) Apr 18, 2024 pm 09:43 PM

In September 23, the paper "DeepModelFusion:ASurvey" was published by the National University of Defense Technology, JD.com and Beijing Institute of Technology. Deep model fusion/merging is an emerging technology that combines the parameters or predictions of multiple deep learning models into a single model. It combines the capabilities of different models to compensate for the biases and errors of individual models for better performance. Deep model fusion on large-scale deep learning models (such as LLM and basic models) faces some challenges, including high computational cost, high-dimensional parameter space, interference between different heterogeneous models, etc. This article divides existing deep model fusion methods into four categories: (1) "Pattern connection", which connects solutions in the weight space through a loss-reducing path to obtain a better initial model fusion

Detailed tutorial on establishing a database connection using MySQLi in PHP Detailed tutorial on establishing a database connection using MySQLi in PHP Jun 04, 2024 pm 01:42 PM

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

How to handle database connection errors in PHP How to handle database connection errors in PHP Jun 05, 2024 pm 02:16 PM

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.

More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques More than just 3D Gaussian! Latest overview of state-of-the-art 3D reconstruction techniques Jun 02, 2024 pm 06:57 PM

Written above & The author’s personal understanding is that image-based 3D reconstruction is a challenging task that involves inferring the 3D shape of an object or scene from a set of input images. Learning-based methods have attracted attention for their ability to directly estimate 3D shapes. This review paper focuses on state-of-the-art 3D reconstruction techniques, including generating novel, unseen views. An overview of recent developments in Gaussian splash methods is provided, including input types, model structures, output representations, and training strategies. Unresolved challenges and future directions are also discussed. Given the rapid progress in this field and the numerous opportunities to enhance 3D reconstruction methods, a thorough examination of the algorithm seems crucial. Therefore, this study provides a comprehensive overview of recent advances in Gaussian scattering. (Swipe your thumb up

An in-depth analysis of how HTML reads the database An in-depth analysis of how HTML reads the database Apr 09, 2024 pm 12:36 PM

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.

Revolutionary GPT-4o: Reshaping the human-computer interaction experience Revolutionary GPT-4o: Reshaping the human-computer interaction experience Jun 07, 2024 pm 09:02 PM

The GPT-4o model released by OpenAI is undoubtedly a huge breakthrough, especially in its ability to process multiple input media (text, audio, images) and generate corresponding output. This ability makes human-computer interaction more natural and intuitive, greatly improving the practicality and usability of AI. Several key highlights of GPT-4o include: high scalability, multimedia input and output, further improvements in natural language understanding capabilities, etc. 1. Cross-media input/output: GPT-4o+ can accept any combination of text, audio, and images as input and directly generate output from these media. This breaks the limitation of traditional AI models that only process a single input type, making human-computer interaction more flexible and diverse. This innovation helps power smart assistants

See all articles