The steps for jdbc to connect to the database: 1. Load the jdbc driver; 2. Create a database connection; 3. Create a preparedStatement; 4. Execute SQL statements; 5. Traverse the result set; 6. Handle exceptions and close JDBC Object resources.
The operating environment of this article: windows10 system, java 1.8, thinkpad t480 computer.
JDBC connects to the database and creates a program to connect to the database with JDBC, including the following steps:
First prepare the four parameters required by JDBC (user, password, url, driverClass)
(1) user name
(2) password
(3) URL defines the protocol, sub-protocol, and data source identifier when connecting to the database. Separate with colons. Writing form: Protocol: Subprotocol: Data source identifier
Protocol: Always starts with jdbc in JDBC
Subprotocol: It is the driver of the bridge connection or the name of the database management system.?
? Data source identification: Mark the address and connection port where the database source is found.? ?
? For example: (MySql connection URL) ? ?
? jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk ? ? ?
? useUnicode=true: Indicates the use of the Unicode character set. If characterEncoding is set to gb2312 or GBK, this parameter must be set to true. characterEncoding=gbk: character encoding method.
For example: ??
try{//加載MySql的驅(qū)動類 Class.forName("com.mysql.jdbc.Driver") ; }catch(ClassNotFoundException e){ System.out.println("找不到驅(qū)動程序類 ,加載驅(qū)動失??!"); e.printStackTrace() ; }After successful loading, the instance of the Driver class will be registered to the DriverManager class.?
? ?Use DriverManager’s getConnectin(String url, String username, String password) method to obtain the path to the specified database to be connected, the username and password of the database.
//連接MySql數(shù)據(jù)庫,用戶名和密碼都是root String url = "jdbc:mysql://localhost:3306/test" ; String username = "root" ; String password = "root" ; try{ Connection con = DriverManager.getConnection(url , username , password ) ; }catch(SQLException se){ System.out.println("數(shù)據(jù)庫連接失?。?quot;); se.printStackTrace() ; }3. Create a preparedStatement ? ? ?To execute a SQL statement, you must obtain a java.sql.Statement instance. The Statement instance is divided into the following 3 Types: ?
1. Execute static SQL statements. Usually implemented through Statement instances.??
? 2. Execute dynamic SQL statements. Usually implemented through a PreparedStatement instance.??
? 3. Execute the database stored procedure. Usually implemented through a CallableStatement instance.
?Specific implementation method:
Statement stmt = con.createStatement();
PreparedStatement pstmt = con.prepareStatement(sql);
CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;
1. ResultSet executeQuery( String sqlString): Execute the SQL statement to query the database and return a result set (ResultSet) object.
2. int executeUpdate(String sqlString): used to execute INSERT, UPDATE or DELETE statements and SQL DDL statements, such as: CREATE TABLE and DROP TABLE, etc.
3. execute(sqlString): used to execute multiple returns Statements with result sets, multiple update counts, or a combination of both.
? Specific implementation code:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...");
int rows = stmt.executeUpdate("INSERT INTO ...");
boolean flag = stmt.execute(String sql);
兩種情況:
1、執(zhí)行更新返回的是本次操作影響到的記錄數(shù)。
2、執(zhí)行查詢返回的結果是一個ResultSet對象。
? ResultSet包含符合SQL語句中條件的所有行,并且它通過一套get方法提供了對這些
行中數(shù)據(jù)的訪問。
? 使用結果集(ResultSet)對象的訪問方法獲取數(shù)據(jù):
while(rs.next()){
String name = rs.getString("name") ;
String pass = rs.getString(1) ; // 此方法比較高效
}
(列是從左到右編號的,并且從列1開始)
6、處理異常,關閉JDBC對象資源
?操作完成以后要把所有使用的JDBC對象全都關閉,以釋放JDBC資源,關閉順序和聲 明順序相反:
1、先關閉requestSet
2、再關閉preparedStatement
3、最后關閉連接對象connection
if(rs !=null){ // 關閉記錄集 try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt !=null){ // 關閉聲明 try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn !=null){ // 關閉連接對象 try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } }
相關視頻教程:java視頻教程
The above is the detailed content of What are the steps to connect to the database using jdbc?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

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)

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

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

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.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

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.
