In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces you what the jdbc connection database code and steps are, the content is very detailed, interested friends can refer to, hope to be helpful to you.
1. Load the JDBC driver
Before JDBC connects to the database, you first need to load the database driver to be connected to JVM (Java virtual machine).
We can do this through the static method forName (StringclassName) of the java.lang.Class class.
Examples are as follows:
Try {
/ / load the driver class of MySql
Class.forName ("com.mysql.jdbc.Driver")
} catch (ClassNotFoundExceptione) {
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. Second, the URL that provides JDBC connection
The connection URL defines the protocols, subprotocols, and data source identities when connecting to the database.
Written 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.
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 the database, you need to request from java.sql.DriverManager and get the Connection object
The object represents a connection to a database.
Using getConnectin (Stringurl,Stringusername) of DriverManager
Stringpassword) method passes in the specified path to the database to connect to, the user name of the database, and
To get the password.
Examples are as follows:
/ / Connect to the MySql database. The username and password are root.
Stringurl= "jdbc:mysql://localhost:3306/test"
Stringusername= "root"
Stringpassword= "root"
Try {
Connectioncon=
DriverManager.getConnection (url,username,password)
} catch (SQLExceptionse) {
System.out.println ("Database connection failed!")
Se.printStackTrace ()
}
4. Create a Statement
To execute the SQL statement, you must obtain a java.sql.Statement instance, which is divided into the following 3 Statement instances
Type:
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:
Statementstmt=con.createStatement ()
PreparedStatementpstmt=con.prepareStatement (sql)
CallableStatementcstmt=
Con.prepareCall ("{CALLdemoSp (?)}")
5. Execute the SQL statement
The Statement interface provides three methods for executing SQL statements: executeQuery and executeUpdate
And execute
1. ResultSetexecuteQuery (StringsqlString): execute the SQL statement that queries the database
Returns a result set (ResultSet) object
2. IntexecuteUpdate (StringsqlString): used to execute INSERT, UPDATE, or
DELETE statements and SQLDDL statements, such as CREATETABLE and DROPTABLE
3. Execute (sqlString): used to execute objects that return multiple result sets, multiple update counts, or a combination of both
Statement.
The code for the specific implementation:
ResultSetrs=stmt.executeQuery ("SELECT*FROM...")
Introws=stmt.executeUpdate ("INSERTINTO...")
Booleanflag=stmt.execute (Stringsql)
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.
Use the access method of the result set (ResultSet) object to get the data:
While (rs.next ()) {
Stringname=rs.getString ("name")
Stringpass=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 and turn off sequence harmony.
The order is opposite:
1. Close the recordset
2. Close the statement
3. Close the connection object
If (rswatches null) {/ / close the recordset
Try {
Rs.close ()
} catch (SQLExceptione) {
E.printStackTrace ()
}
}
If (stmtpacking null) {/ / close the declaration
Try {
Stmt.close ()
} catch (SQLExceptione) {
E.printStackTrace ()
}
}
If (connected connection null) {/ / close the connection object
Try {
Conn.close ()
} catch (SQLExceptione) {
E.printStackTrace ()
}
}
On the jdbc connection database code and steps what is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
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.