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){ }
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){ }
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){ }
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 表的名称");//读取表中特定的列
getXxx(int columnIndex) and obtain the column value by passing the column name
getXxx(String columnName).
(3) Close the connection
con.close(); //关闭con所连接的数据库
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指定的行(参数取负数即倒数)
(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!='李四'(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'%欧%' //查询name字段有“欧”字的记录
select * from table order by height select * from table where name like '%王%' order by name
3. Update, add and delete operations
Statement object callpublic 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 <条件子句>
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代表要替换的值。
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();
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);
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();
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();
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!

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

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

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

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

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.

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 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;
