search
HomeDatabaseMysql TutorialJDBC的进阶知识和语法[以mysql为例作Demo]_MySQL

bitsCN.com

 

一丨Statement

1.1 PerparedStatement (准备Statement,解决参数类型问题)

 

	public static PreparedStatement getPreparedStatement(Connection conn,String sql){		try {			pstmt = conn.prepareStatement(sql);		} catch (SQLException e) {			System.err.println("*Faild In CreateStatement By Connection");			e.printStackTrace();		}		return pstmt;	}

 

package com.qsuron.util;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import com.qsuron.util.DB;public class Test2 {	public static void main(String[] args) throws SQLException {		Connection conn = DB.getConnection("jdbc:mysql://xxx.xxx.xxx.xxx:xxxx/qsuron","qsuron","qsuron");		PreparedStatement pstmt = DB.getPreparedStatement(conn,"insert into student values(?,?,?);");		pstmt.setInt(1,1213400129);		pstmt.setString(2,"123456");		pstmt.setString(3,"qsuron");		pstmt.executeUpdate();		DB.close();	}}

 

 

1.2 CallableStatement (存储过程)

创建一个存储过程

CREATE DEFINER=`root`@`localhost` PROCEDURE `p`(IN `id1` int,IN `id2` int,IN `password` char(20),IN `name` varchar(15),OUT `temp` int)BEGIN#插入id较大的,返回表中数据数IF(id1>id2)THENSET temp = id1;ELSESET temp = id2;end if;INSERT into student VALUES(temp,password,name);select COUNT(*) INTO temp from student;END
	public static CallableStatement getCallableStatement(Connection conn,String sql){		try {			pcstmt = conn.prepareCall(sql);					} catch (SQLException e) {			System.err.println("*Faild In CreateStatement By Connection");			e.printStackTrace();		}		return pcstmt;	}

 

package com.qsuron.test;import java.sql.CallableStatement;import java.sql.Connection;import java.sql.SQLException;import java.sql.Types;import com.qsuron.util.DB;public class Test3 {	public static void main(String[] args) throws SQLException {		Connection conn = DB.getConnection();		CallableStatement pcstmt = DB.getCallableStatement(conn,"{call p(?,?,?,?,?)}");		pcstmt.setInt(1,1213400103);		pcstmt.setInt(2,1213400104);		pcstmt.setString(3,"123456");		pcstmt.setString(4,"qsuron");		pcstmt.registerOutParameter(5,Types.INTEGER);		pcstmt.execute();		System.out.println("Return : " + pcstmt.getInt(5));		DB.close();	}}

 


1.XX 未完待续




 

二丨Batch 批处理

 

package com.qsuron.test;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import com.qsuron.util.DB;public class Test4 {	public static void main(String[] args) throws SQLException {		Connection conn = DB.getConnection();		Statement stmt = DB.getStatement(conn);		stmt.addBatch("insert into student values ('1213400131','1','Q');");		stmt.addBatch("insert into student values ('1213400132','1','Q');");		stmt.addBatch("insert into student values ('1213400133','1','Q');");		stmt.executeBatch();		DB.close();	}}
同理,PreparedStatement 也可使用Batch

 

 

package com.qsuron.test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import com.qsuron.util.DB;public class Test5 {	public static void main(String[] args) throws SQLException {		Connection conn = DB.getConnection();		PreparedStatement pstmt = DB.getPreparedStatement(conn,"insert into student values(?,?,?);");		pstmt.setInt(1,1213400141);		pstmt.setString(2,"1");		pstmt.setString(3,"Q");		pstmt.addBatch();						pstmt.setInt(1,1213400142);		pstmt.setString(2,"1");		pstmt.setString(3,"Q");		pstmt.addBatch();						pstmt.setInt(1,1213400143);		pstmt.setString(2,"1");		pstmt.setString(3,"Q");		pstmt.addBatch();				pstmt.executeBatch();				DB.close();	}}


 

三丨继Batch之Transaction Google翻译

 

缘由:如A转账予B,那么JDBC至少要操作2条UPDATE语句(A减B加),Transaction就是为了保证这两条语句必须同时执行成功或者同时执行失败。

 

package com.qsuron.test;import java.sql.Connection;import java.sql.SQLException;import java.sql.Statement;import com.qsuron.util.DB;public class Test6 {	public static void main(String[] args) throws SQLException {		Connection conn = DB.getConnection();		Statement stmt = DB.getStatement(conn);		try {			conn.setAutoCommit(false);			//将自动提交设置为false,将多条语句积累到一起			stmt.addBatch("insert into student values ('1213400135','1','Q');");			stmt.addBatch("insert into student values ('1213400136','1','Q');");			stmt.addBatch("insert into student values ('1213400134','1','Q');");			stmt.executeBatch();			conn.commit();			//执行			conn.setAutoCommit(true);			//重置自动提交		} catch (Exception e) {			//如果抓到异常就现场恢复			if(conn!=null){				conn.rollback();				//数据回滚				System.out.println("Exception:Rollback!");				conn.setAutoCommit(true);			}		}		DB.close();	}}
测试方法:让中间的语句的id发生主键唯一错误。

 

四丨ResultSet 结果集

 

1.前后滚动机制

 

package com.qsuron.test;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import com.qsuron.util.DB;public class Test7 {	public static void main(String[] args) throws SQLException {		Connection conn = DB.getConnection();		Statement stmt = DB.getStatement(conn,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);		ResultSet rs = DB.query(stmt,"select * from student order by id;");		rs.last();		System.out.println("当前行数:"+rs.getRow());		System.out.println(rs.getString(1));		rs.previous();		System.out.println(rs.getString(1));		rs.absolute(7);		System.out.println(rs.getString(1));		DB.close();	}}

 

2.JDBC之ResultSet对象-注意事项(点击前往)

 

转载请注明出处:blog.csdn.net/qsuron 小树博客(qsuron)

bitsCN.com
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
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

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.

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.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function