Java Learning Notes--JDBC use of the database

Source: Internet
Author: User

reference Hu_shengyang's column: http://blog.csdn.net/hu_shengyang/article/details/6290029

The classes and interfaces for common database programming provided in the JDBC API are as follows

1.Driver Interface: Representative driver

Class 2.DriverManager: Driver administrator

3.Connection interface: Represents a database connection

4.Statement, PreparedStatement, CallableStatement interface: Represents the database Operation object

5.ResultSet interface: Represents the result set

6.DatabaseMetadata, ResultSetMetaData interface: Represents metadata

Class 7.Types: Representing the JDBC type

Detailed explanation

2.DriverManager class

The DriverManager class manages basic services for a set of JDBC drivers, tracks available drivers, and establishes a connection between the database and the appropriate driver to handle transactions such as the driver logon time limit and the display of logon and trace messages.

First use the DriverManager class to load the drive, and use the class's Drivermanager.registerdriver (Driver Driver) method to register the drive. (The Registerdriver method is a static method that can be called directly from the class name).

There are two ways to load a drive

(1) Drivermanager.registerdriver (Driver Driver), the driver column in DriverManager can be used to create the connection

(2) The Load driver class is displayed by calling method Class.forName () . Because it is not related to external settings, it is recommended

String Driver = "Com.microsoft.sqlserver.jdbc.SQLServerDriver"; class. forname (driver);

Common methods: Drivermanager.getconnection (), the parameters are different, there are some of the following

Drivermanager.getconnection (String URL);

Drivermanager.getconnection (string url, string user, string password); User is the database username, password is the database password

3.Connection interface

When the Drivermanager.getconnection method is called to make a connection request, DriverManager checks to see if each driver can make a connection and returns a connection database connection object.

The Createstatement () method creates a state object to send SQL statements to the database, and SQL statements with no parameters are typically executed using the statement object, and if you execute the same SQL statement more than once, you can use the PreparedStatement method

Example: Statement stmt = Dbconn.createstatement ();

4.Statement interface

Send the SQL statement to the database.

JDBC has 3 types of Statement objects, Statement, PreparedStatement (inherited from Statement), CallableStatement (inherited from PreparedStatement)

The statement interface provides 3 ways to execute SQL statements

(1) ExecuteQuery () is used to produce a single result set statement, such as SELECT, that returns a single Resuleset object

(2) Executeupdate () execution of data manipulation languages such as insert,update,delete statements, and CREATE table and DROP table Data Definition Language

(3) Execute () executes statements that return multiple result sets, multiple updates, or a combination of the two

5.ResultSet interface

Contains all rows that conform to the conditions in the SQL statement, and provides access to the data in those rows through a set of Get methods.

Resultset.next moves to the next row of records GetXXX () Gets the data in the specified column

Third, the basic steps of the JDBC application:

1. Registration Driver

2. Establishing a database connection

3. Create a Database Action object

4. Execute SQL

5. Working with result sets

6. Close the JDBC Object

1. Register a DRIVER driver

Three ways to register a driver:

Mode one: Class.forName ("Oracle.jdbc.driver.OracleDriver");

Mode two: Driver driver=new Oracle.jdbc.driver.OracleDriver ();

Drivermanager.registerdriver (driver);

Method Three: Load the driver in the virtual machine at compile time

javac-d jdbc.drivers = Oracle.jabc.driver.OracleDriver Xxx.java

java-d jabc.drivers = driver Full Name Class name

Use system property name, load driver-D to assign values to System properties

Attached: MySQL Driver full name: Com.mysql.jdbc.Driver

Driver full name of SQL Server: Com.microsoft.jdbc.sqlserver.SQLServerDriver

2. Establish a connection

Conn=drivermanager.getconnection

("Jdbc:oracle.thin:@192.168.0.254:1521/test", "username", "password");

    The above brackets are: Oracle Self-Protocol [email protected]+ip:port/ DB instance name, database user name, user password.

    mysql URL notation : jdbc:mysql://192.168.254:3306/test

    SQL Server URL notation : jdbc:sqlserver://localhost:1433; Databasename=ztest

Supplement to other information (not proven correct)

  Oracle (thin mode):jdbc:oracle:thin: @localhost: 1521:orcl//ORCL is the SID of the database

  Sybase:jdbc:sybase:tds:localhost:5007/mydb//mydb for database name

  DB2: jdbc:db2://localhost:5000/mydb

  MySQL: jdbc:mysql://localhost/mydb?user=soft&password=123&useunicode=true& Characterencoding=8859_1

3. Get a Statement object

STA = Conn.createstatement ();

4. Executing SQL statements via statement

Sta.excutequery (SQL);//Returns a query result set

Sta.executeupdate (SQL);//The return value is of type int, which indicates the number of bars affecting the record

The SQL statement is sent through the connection to the database for execution in order to perform operations on the database.

5. Working with result sets

Use the Connection object to obtain a executequery (String sql) method in a stagement,statement that can be queried using a SELECT statement and return a result set ResultSet. By traversing the result set, you can obtain the query results for the SELECT statement. The next () method of resultset will manipulate a cursor to begin reading from the first record until the last day of recording. The executeupdate (String sql) method is used to execute DDL/DML statements, such as Update,delete.

Only a SELECT statement returns a result set.

Example: Statement sta = con.createstatement (); Create a statement object

String sql = "INSERT INTO Test (Id,name) VALUES (1" + "" "" + "King" + "" "" + ")";

Sta.executeupdate (SQL); Execute SQL statement

String sql = "SELECT * from Test";

Reslutset rs = sta.executequery (sql);//result set after executing SQL statement

Traversal processing result set

while (Rs.next ()) {

System.out.println (Rs.getint ("id"));

System.out.println (rs.getstring ("name"));

}

6. Closing the database connection (freeing resources)

Call the Close () method:

Rs.close ();

Sta.close ();

Conn.close ();

ResultSet, Statement, and connetction are in turn dependent.

Note: To close the resource in the order of first ResultSet, then statement, and finally connetction. Because ResultSet and statement can be used in the case of connection, there may be other statement connected after the use of the bundle, so the connection cannot be closed first.

======================================

Example

Create a new database ztest within SQL Server and run the following statement

Build table:

CREATE TABLE Student (
Sno Char (9) PRIMARY KEY,
Sname Char (20),
Ssex Char (2)
)

insert data:

insert into Student values (' 1000002 ', ' Zhang Yi ', ' f ');
insert into Student values (' 1000003 ', ' Zhang San ', ' f ');
insert into Student values (' 1000004 ', ' Zhang Si ', ' f ');
insert into Student values (' 1000005 ', ' Five ', ' m ');
insert into Student values (' 1000006 ', ' Six ', ' f ');
insert into Student values (' 1000007 ', ' seven ', ' m ');
insert into Student values (' 1000008 ', ' eight ', ' m ');

public class Test {public static void main (String[]args) {String drivername = " Com.microsoft.sqlserver.jdbc.SQLServerDriver ";  Load JDBC Driver string dburl = "jdbc:sqlserver://localhost:1433; Databasename=ztest ";  Connect server and database teststring userName = "sa";  Default User name string userpwd = "123";  Password Connection dbconn = null;try {class.forname (drivername);d bconn = Drivermanager.getconnection (Dburl, UserName, USERPWD); System.out.println ("Connection successful!");  If the connection succeeds console output connection successful!} catch (Exception e) {e.printstacktrace (); System.out.println ("Connection failed ..."); try {Statement stmt = dbconn.createstatement (); Stmt.executeupdate ("INSERT into Student values (' 22222222 ', ' John Doe ', ' m ');"); ResultSet rs = stmt.executequery ("SELECT * from Student"), while (Rs.next ()) {System.out.println (rs.getstring ("sno") + "" +rs.getstring ("sname") + "" "+rs.getstring (" Ssex "));}} catch (SQLException e) {e.printstacktrace ();}}}

  

Console results

Connection successful!1000001    Zhang                  1000002    Zhang Yi                  1000003    Zhang San                  1000004 Zhang    four                  1000005    Zhang five                  1000006    Zhang six                  1000007    Zhang Qi                  1000008    Zhang eight                  22222222  John Doe                 

Java Learning Notes--JDBC use of the database

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.