Java Database Programming Learning notes constantly updated

Source: Internet
Author: User

Recently began to learn Java, feel Java database programming needs to send an essay record, words do not say cut into the topic.

A Introduction to Database Access technology

application → Execute SQL statement → database → retrieve data results → application

(ODBC JDBC (two common APIs))

Java primarily uses the JDBC driver to program the database

               Java Applications <------> JDBC <------> Databases

Two Architecture of JDBC

Application Layer

↓

Drive Layer

↓

Each interface

Driver Connection Statement resultset

Three java.sql. Package

Interface Name

Description

Connection

This interface represents the connection to the data

PreparedStatement

This interface is used to perform precompiled SQL statements

ResultSet

This interface represents a query of the database data result set

Statement

This interface is used to execute SQL statements and retrieve data into ResultSet

class name

description

DriverManager

This class is used to load and unload various drivers and establish a connection to the database

Date

This class contains various ways to convert the SQL date format to the Java date format

time

This class is used to represent time

TimeStamp

This class provides greater accuracy by adding the nanosecond field

Four JDBC Programming Essentials

When using a database for JDBC programming in Java, Java programs typically contain the following sections:

(1) The java.sql package is introduced into the program with the import statement at the first of the program:

Import java.sql.*;

(2) Use the Class.forName () method to load the JDBC driver for the corresponding database. To load the Jdbc-odbc bridge as an example, the corresponding statement format is:

Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");

(3) A URL object that defines the JDBC. For example: String conurl= "Jdbc:odbc:TestDB";

Where TestDB is the data source that we set up to create.

(4) Connect to the database.

Connection s=drivermanager.getconnection (Conurl);

(5) Use the SQL statement to manipulate the database.

(6) Use the Close () method to disassociate Java from the database and close the database.

For example: S.close ();

Five Database connection Steps-1

Create a program that connects to the database in JDBC with 7 steps:
1. Load the JDBC driver:
Before connecting to a database, you first load the driver of the database you want to connect to the JVM (Java Virtual machine), which is implemented by the static method forname (String className) of the Java.lang.Class class. For example:
try{
Load the MySQL driver class
Class.forName ("Com.mysql.jdbc.Driver");
Load Oracle Driver
Class.forName ("Oracle.jdbc.driver.OracleDriver");
Load SQL Server Driver
Class.forName ("Com.microsoft.jdbc.sqlserver.SQLServerDriver");
}catch (ClassNotFoundException e) {
System.out.println ("Driver class not found, load driver failed!") ");
E.printstacktrace ();
}

After a successful load, an instance of the driver class is registered in the DriverManager class.

Step-2

Provide a URL for the JDBC connection
• The connection URL defines the protocol, sub-protocol, and data source identity when the database is connected.
• Written form: protocol: Sub-Protocol: Data source identification
Protocol: Always start with JDBC in JDBC
Sub-Protocol: A bridge-connected driver or database management system name.
Data source identification: The tag locates the address of the database source and the connection port.
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.
Can also be expressed as:
String url= "Jdbc:mysql://localhost:3306/test"; Mysql
Stringurl= "Jdbc:oracle:thin: @localhost: 1521:ORCL"; ORCL the SID for the database
String url= "Jdbc:microsoft:sqlserver://localhost:1433;databasename=mydb";//URL that connects to SQL Server

Step-3

Create a connection to a database
. • To connect to a database, you need to request and obtain a Java.sql.DriverManagerConnectionObject, the object represents a connection to a database
• Use DriverManager's getconnectin (string URL, String Username,stringpassword) method to obtain the path to the specified database to connect to, the user name of the database, and the password.
For example:
Connect to MySQL database, user name and password are root
String url = "Jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "root";
try{
connectioncon=drivermanager.getconnection (Url,username,password);
}catch (SQLException se) {
SYSTEM.OUT.PRINTLN ("Database connection failed! ");
Se.printstacktrace ();
}

Step-4

Create a statement
• To execute an SQL statement, you must obtain an java.sql.Statement instance, and the statement instance is divided into the following 3 types:
1. Execute static SQL statements. Typically implemented through statement instances.
2. Execute dynamic SQL statements. Typically implemented through PreparedStatement instances.
3. Execute the database stored procedure. Typically implemented through CallableStatement instances.
The specific implementation method:
Statement stmt = Con.createstatement ();
PreparedStatement pstmt =con.preparestatement (SQL);
CallableStatement cstmt =con.preparecall ("{Call Demosp (?,?)}");

Step-5

Execute SQL statement
The statement interface provides three ways to execute 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, as well as SQL DDL statements, such as CREATE table and drop table, etc. (returns the number of data records affected)
3. Execute (sqlString): Used for execution to return multiple result sets, multiple update counts, or both combined statements.
Specific implementation code:
ResultSet rs =stmt.executequery ("Select * from ...");
int rows = stmt.executeupdate ("Insertinto ...");
Boolean flag = Stmt.execute (String sql);

Step-6

   processing results    
      two cases:    
         1, performing the update returns the number of records affected by this operation.    
        2, the result returned by the execution query is a ResultSet object.    
       resultset contains all rows that conform to the conditions in the SQL statement, and it provides access to the data in those rows through a set of Get methods.    
      gets data using the access method of the result set (ResultSet) object:    
        while (Rs.next ()) {   
             String name= rs.getstring ("name");    
             String pass= rs.getstring (1); This method is efficient (columns are numbered from left to right and starting with column 1)    
      }         

Step-7

Close the JDBC Object
After the operation is complete, all the JDBC objects used are closed to release the JDBC resource, and the order of closing and declaration is reversed:
1. Close record set
2. Closing the statement
3. Close the Connection object

4/7/2015 9:20:44 PM H.YF Records

References "Java Programming practical Treasure" Tsinghua University Press Liu Xin, Tai Lei and other authoring

Java Database Programming Learning notes constantly updated

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.