Steps for connecting jdbc to the database

Source: Internet
Author: User

Steps for connecting jdbc to the database
Create a program to connect to the database using JDBC, which contains seven steps:
1. Load the JDBC driver:
Before connecting to the database, load the driver of the database to be connected to the JVM (Java Virtual Machine ),
This is achieved through the static method forName (String className) of the java. lang. Class.
The Code is as follows:

<Span style = "font-size: 18px;"> try {// load the MySql Driver Class. forName ("com. mysql. jdbc. driver ");} catch (ClassNotFoundException e) {System. out. println ("The driver class cannot be found. Failed to load the driver! "); E. printStackTrace () ;}</span>


After the Driver class is loaded, the Driver class instance is registered to the DriverManager class.

2. Provide the URL of the JDBC connection
• The Connection URL defines the protocol, sub-protocol, and data source identification used to connect to the database.
• Writing format: Protocol: Sub-Protocol: data source ID
Protocol: always starts with JDBC in jdbc.
Sub-Protocol: the name of the Bridge Connection driver or database management system.
Data source ID: Mark the address and connection port of the database source.
Example: (MySql connection URL)
<Span style = "font-size: 18px;"> jdbc: mysql: // localhost: 3306/test? UseUnicode = true & characterEncoding = gbk; useUnicode = true: indicates that the Unicode character set is used. If characterEncoding is set to gb2312 or GBK, this parameter must be set to true. CharacterEncoding = gbk: character encoding method. </Span>


3. Create a database connection
• To connect to the database, you must request java. SQL. DriverManager and obtain the Connection object,
This object represents a database connection.
• Use getConnectin (String url, String username,
String password ).
Password.
The Code is as follows:
<Span style = "font-size: 18px;"> // connect to the MySql database. The username and password are both rootString 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 () ;}</span>




4. Create a Statement
• To execute an SQL Statement, you must obtain the java. SQL. Statement instance. The Statement instance is divided into three types:
Type:
1. Execute static SQL statements. It is usually implemented through a Statement instance.
2. Execute dynamic SQL statements. It is usually implemented through the PreparedStatement instance.
3. Execute the database stored procedure. It is usually implemented through the CallableStatement instance.
The Code is as follows:
<span style="font-size:18px;">Statement stmt = con.createStatement() ;PreparedStatement pstmt = con.prepareStatement(sql) ;CallableStatement cstmt =con.prepareCall("{CALL demoSp(? , ?)}") ; </span>




5. Execute SQL statements
The Statement interface provides three methods for executing SQL statements: executeQuery and executeUpdate.
And execute
1. ResultSet executeQuery (String sqlString): run the SQL statement used to query the database.
Returns a result set 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
3. execute (sqlString): used for executing and returning multiple result sets, multiple update counts, or a combination
Statement.
Specific implementation code:


<span style="font-size:18px;">ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;int rows = stmt.executeUpdate("INSERT INTO ...") ;boolean flag = stmt.execute(String sql) ; </span>




6. processing result
Two cases:
1. The number of records affected by this operation is returned when an update is executed.
2. The result returned by executing the query is a ResultSet object.
• The ResultSet contains all rows that meet the conditions in the SQL statement, and provides
The data in the row.
• Use the access method of the result set object to obtain data:


<Span style = "font-size: 18px;"> while (rs. next () {String name = rs. getString ("name"); String pass = rs. getString (1); // This method is more efficient} </span>



(Columns are numbered from left to right and start from column 1)

7. Disable JDBC objects
After the operation is completed, all the used JDBC objects should be closed to release the JDBC resources, close the sequence and
Reverse Order:
1. Disable record set
2. Close the statement
3. Close the connection object


<Span style = "font-size: 18px;"> if (rs! = Null) {// close record set try {rs. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (stmt! = Null) {// close the Declaration try {stmt. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (conn! = Null) {// close the connection object try {conn. close () ;}catch (SQLException e) {e. printStackTrace () ;}</span>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.