Home Java JavaBase Java program development learning JDBC and MySQL database

Java program development learning JDBC and MySQL database

Feb 11, 2021 am 10:33 AM
java jdbc mysql database

Java program development learning JDBC and MySQL database

Relevant learning recommendations: java basics

##1. JDBC connection to the database operation

You can encapsulate it in a class to simplify the code when writing.

(1) Load the JDBC-MySQL database driver

try {
    Class.forName("com.mysql.cj.jdbc.Driver");}catch (Exception e){ }
Copy after login
(2) Connect to the database

Connection con = null;//声明要连接数据库的对象comString uri = "jdbc:mysql://localhost:3306/数据库名?useSSL=true &characterEncoding=utf-8";	//连接地址String user = "root";	//连接数据库的用户名String password = "123456";	//连接数据库的密码try {
    con = DriverManager.getConnection(uri,user,password);
	//连接代码}catch(SQLException e){ }
Copy after login
(3) Write the code to operate the data in the database

2. Query operation

1, specific steps of query operation (1) Send SQL statement to the database:

Statement sql;try{
    sql = con.createStatement();}catch (SQLException e){ }
Copy after login
First declare the SQL statement object , and then let the created connection object con call the method

createStatement() to create this SQL statement object. (2) Processing query results
With the SQL statement object, this object can call corresponding methods to implement various operations on the tables in the database, where the query results are stored in an object declared by the ResultSet class. That is, the SQL query statement returns a ResultSet object to the database query operation. The ResultSet is composed of data rows organized by "columns" (fields).

rs = sql.executeQuery("select * from 表的名称");//读取表中的所有列,*为通配符rs = sql.executeQuery("select 行1字段名,行2字段名... from 表的名称");//读取表中特定的列
Copy after login
The ResultSet object can only see one row of data at a time, use the next() method to move to the next row. The ResultSet object can obtain the column value through

getXxx(int ​​columnIndex) and obtain the column value by passing the column name getXxx(String columnName). (3) Close the connection

con.close(); //关闭con所连接的数据库
Copy after login
Note: The database is closely bound to the connection object, and the database should be closed after use.

2, control the cursor The initial position of the cursor of the result set is in front of the first row of the result set. The result set calls the next() method to move the cursor downward (back). Returns true if the move is successful and false if the move fails.
If you want to move and display several records in the result set, you must return a scrolling result set. The method is as follows:

Statement stmt = con.createStatement(int type,int concurrency);//获得一个Statement对象,根据参数的值,stmt返回相应类型的结果集:ResultSet re = stmt.executeQuery(SQL语句);type的取值:决定滚动方式:
ResultSet.TYPE_FORWARD_ONLY 结果集的游标只能向下滚动
ResultSet.TYPE_SCROLL_INSENSITIVE 游标可以上下移动,数据库变化时,结果集不变
ResultSet.TYPE_SCROLL_SENSITIVE 返回可滚动的结果集,数据变化时,结果集同步改变
Concurrency取值:决定是否可以用结果集更新数据库
ResultSet.CONCUR_READ_ONLY 不能用结果集更新数据库中的表
ResultSet.CONCUR_UPDATABLE 能用结果集更新数据库中的表

滚动查询常用的ResultSet的方法:public boolean previous() 将游标向上移动,当移动到结果集第一行之前时返回falsepublic void beforeFirst() 将游标移动到结果集的初始位置,第一行之前public void afterLast() 将游标移动到结果集的最后一行之后public void first() 将游标移动到第一行public void last() 将游标移动到最后一行public boolean isAfterLast() 判断游标是否在最后一行之后public boolean isBeforeFirst() 判断游标是否在第一行游标之前public boolean isFirst() 判断游标是否指向第一行public boolean isLast() 判断游标是否指向最后一行public int getRow() 得到当前游标所指向的行号,行号从1开始,如果结果集没有行,返回0public boolean absolute(int row) 将游标移动到参数row指定的行(参数取负数即倒数)
Copy after login

(3) Condition and sorting query where sub-statement:
select field from indicates where condition

(1)字段值与固定值比较
select * from table where name='张三'(2)字段值在某个区间
select * from table where number>5 and number<10 and name!=&#39;李四&#39;(3)使用某些特殊的日期函数(Data:year-month-day)select * from table where year(表明日期的字段名)<1980 and month(表面日期的字段名)<=10select * from table where year(表明日期的字段名) between 2002 and 2021(4)使用某些特殊的时间函数(hour,minute,second)
select * from timelist where second(表明时间的字段名)=36(5)用操作符like进行模式匹配,使用%代替0个或多个字符,用一个下划线_代替一个字符。
select * from table where name like&#39;%欧%&#39; //查询name字段有“欧”字的记录
Copy after login

order by statement: can be used in combination with where statement

select * from table order by height
select * from table where name like &#39;%王%&#39; order by name
Copy after login

3. Update, add and delete operations

Statement object call

public int executeUpdate(String sqlStatement);Update, add and delete records in the database table through the method specified by parameters.

(1)更新
update 表名 set 字段 = 新值 where <条件子句>(2)添加
insert into 表 values (对应具体的记录)(3)删除
delete from 表名 where <条件子句>
Copy after login

4. Use prepared statements

Java provides a more efficient database operation mechanism, which is the PreparedStatement object, that is, the prepared statement object. Process the SQL statement into the underlying statement of the database and then transmit it to the database.

Use wildcards: When preprocessing SQL, you can use the wildcard character ? to replace the field value. Just set the specific value represented by the wildcard character before executing the prepared statement:

String str = "select * from 表名 where 字段1 < ? and 字段2 = ?";PreparedStatement sql = con.prepareStatement(str);sql.setXxx(int parameterIndex,Type x);//该方法设置?代表的值,parameterIndex代表第几个?,x代表要替换的值。
Copy after login

5. General Query

Writing a general query class, the user can pass the database name and SQL statement to the object of this class, and then the object will use a two-dimensional array to return the query record.

Writing a general query class requires knowing the name and number of database table columns (fields). The common method is to use the result set ResultSet object rs to call the
getMetaData() method to return a ResultSetMetaData object:

ResultSetMetaData metaData = rs.getMetaData();
Copy after login
Then the object metaData calls the

getColumnCount() method to return The number of columns in rs, call getColumnName(int i) to return the name of the i-th column in the result set rs.

6. Transaction

1, transaction and processing A transaction consists of a set of SQL statements. The so-called transaction processing means that the application program ensures that either all SQL statements in the transaction are executed or none of them are executed. Transaction processing is an important mechanism to ensure the integrity and consistency of data in the database.

2, JDBC transaction processing Use the setAutoCommit(boolean b) method to turn off the automatic mode:
That is to turn off the immediate effectiveness of the SQL statement, the two related operations should Change the data in the database only after all executions are completed. The method is to let the connection object call this method before obtaining the sql object:

con.setAutoCommit(false);
Copy after login
Use the commit() method to process the transaction:

After turning off the automatic mode, let the sql object submit multiple SQL (that is, the same transaction) statements , these statements will not take effect immediately, but will take effect until the connection object calls the method:

con.commit();
Copy after login
Failed to use the rollback() method to process the transaction:

That is, the operation performed by the transaction is cancelled. When con calls the commit() method for transaction processing, as long as one SQL statement is not executed successfully, the transaction execution fails and a SQLException is thrown. At this time, con must be allowed to call the rollback() method to undo all operations that cause data changes:

con.rollback();
Copy after login

Related free learning recommendations: mysql video tutorial

The above is the detailed content of Java program development learning JDBC and MySQL database. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power Introduction Java is a powerful programming language used in everything from mobile applications to enterprise-level systems. For beginners, Java's syntax is simple and easy to understand, making it an ideal choice for learning programming. Basic Syntax Java uses a class-based object-oriented programming paradigm. Classes are templates that organize related data and behavior together. Here is a simple Java class example: publicclassPerson{privateStringname;privateintage;

See all articles