In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, I will talk to you about how Java creates a program to connect to the database with JDBC. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
JDBC connects to the database
◆ creates a program to connect to the database with JDBC, which consists of seven steps:
1. Load the JDBC driver:
Before connecting to the database, first load the driver of the database you want to connect to to JVM (Java virtual machine), which is achieved through the static method forName (String className) of the java.lang.Class class.
For example:
Try {/ / load MySql's driver class Class.forName ("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {System.out.println ("driver class not found, failed to load driver!") ; e.printStackTrace ();}
When loaded successfully, an instance of the Driver class is registered with the DriverManager class.
2. URL that provides JDBC connection
The ◆ connection URL defines the protocols, subprotocols, and data source identities when connecting to the database.
◆ writing form: protocol: sub-protocol: data source identification
Protocol: always start with jdbc in JDBC
Subprotocol: is the driver of the bridge connection or the name of the database management system.
Data source identification: the tag finds the address and connection port of the database source.
For example: (connection URL of MySql)
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.
3. Create a connection to the database
To connect to a database, ◆ needs to request a java.sql.DriverManager and get a Connection object, which represents a database connection.
◆ uses the getConnectin (String url, String username, String password) method of DriverManager to pass in the specified path to the database to connect to, the user name and password of the database.
For example:
/ / Connect to the MySql database with the username and password of 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 ("Database connection failed!") ; se.printStackTrace ();}
4. Create a Statement
In order for ◆ to execute SQL statements, you must obtain java.sql.Statement instances. Statement instances are divided into the following three types:
1. Execute static SQL statements. It is usually implemented through a Statement instance.
2. Execute dynamic SQL statements. It is usually implemented through a PreparedStatement instance.
3. Execute the database stored procedure. It is usually implemented through a CallableStatement instance.
The specific implementation method:
Statement stmt = con.createStatement (); PreparedStatement pstmt = con.prepareStatement (sql); CallableStatement cstmt = con.prepareCall ("{CALL demoSp (?)}")
5. Execute the SQL statement
The Statement interface provides three methods for executing SQL statements: executeQuery, executeUpdate, and execute
1. ResultSet executeQuery (String sqlString): executes the SQL statement that queries the database and returns 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 statements that return multiple result sets, multiple update counts, or a combination of both.
The code for the specific implementation:
ResultSet rs = stmt.executeQuery ("SELECT * FROM..."); int rows = stmt.executeUpdate ("INSERT INTO..."); boolean flag = stmt.execute (String sql)
6. Processing result
There are two situations:
1. The number of records affected by this operation is returned by performing the update.
2. The result returned by executing the query is a ResultSet object.
◆ ResultSet contains all lines that meet the conditions in the SQL statement, and it provides access to these through a set of get methods
Access to data in the row.
◆ uses the access method of the result set (ResultSet) object to get the data:
While (rs.next ()) {String name = rs.getString ("name"); String pass = rs.getString (1); / / this method is more efficient}
(columns are numbered from left to right, starting with column 1)
7. Close the JDBC object
After the operation is completed, all used JDBC objects should be closed to release JDBC resources, in reverse order of declaration:
1. Close the recordset
2. Close the statement
3. Close the connection object
If (rs! = null) {/ / close recordset try {rs.close ();} catch (SQLException e) {e.printStackTrace ();}} if (stmt! = null) {/ / close statement try {stmt.close ();} catch (SQLException e) {e.printStackTrace ();}} if (conn! = null) {/ / close connection object try {conn.close ();} catch (SQLException e) {e.printStackTrace () }} after reading the above, do you have any further understanding of how Java creates a program that connects to a database with JDBC? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.