Java Study Notes-JDBC1 (16), study notes jdbc1

Source: Internet
Author: User

Java Study Notes-JDBC1 (16), study notes jdbc1

1, Data persistence

L persistence: saves data to a power-down storage device for later use, also known as "Curing ". In most cases, data persistence in server or client applications is achieved through relational databases.

L storage devices: disks, hard disks, USB disks, and optical disks

L Storage Format: databases, xml files, txt files, etc.

2Knowledge Point 2: JavaData Storage Technology in

L in Java, database access technology can be divided into the following categories:

L direct JDBC access to the database

L third-party O/R tools, such as Hibernate and ibatis

L JDBC is the cornerstone of java database access, and other technologies are encapsulation of jdbc

3What is JDBC?

L JDBC (Java Database Connectivity) is an Interface (a set of Apis) independent of specific Database management systems and general Database operations. It defines a standard Java class library for accessing databases, the implementation of interfaces is completed by various database vendors.

L JDBC Driver (jar package): a set of implementation classes (jar packages) implemented by database vendors for JDBC Interfaces)

4What is ODBC

L ODBC (Open Database Connectivity, Open Database connection) is an integral part of the Open service structure of Microsoft. It establishes a set of specifications, and provides a set of standard APIs for database access.

5, JDBCCategory

There are currently four available JDBC drivers. Different types of drivers have different usage methods, so before we connect to the database, you must first select an appropriate driver as needed. The four different types of drivers are:

1 JDBC-ODBC Bridge: bridge-type driver,

2. Local APIs and Java drivers are also one of the bridge drivers.

3 JDBC network pure Java driver

4 Local protocol pure Java driver: This type of driver is the most mature JDBC driver, not only does not need to install any additional driver on the user's computer, you do not need to install any middleware (middleware) on the server. All database access operations are directly completed by the driver.

6. Introduction to JDBC APIs

Public class Test1 {public static void main (String [] args) throws Exception {// 1. register the driver (which can be connected to the database) DriverManager. registerDriver (new Driver (); // 2. obtain the Connection con = DriverManager object connected to the database. getConnection ("jdbc: mysql: // 127.0.0.1: 3306/mydb", "root", "root"); // 3. get an execution SQL object Statement stm = con. createStatement (); // 4. execute SQL statements. take the query as an example. After execution, a ResultSet result set is returned. (It actually contains the queried information) ResultSet rs1_0000.exe cuteQuery ("select * from emp"); // table name // 5. iterate the content in the result set. while (rs. next () {Object obj = rs. getObject ("ename"); // query the column name System. out. println (obj);} // 6. resources need to be released rs. close (); stm. close (); con. close ();}}

8. Exception Handling for the above Code:

// JDBC exception handling public class Test3 {public static void main (String [] args) {Connection con = null; Statement stm = null; ResultSet rs = null; try {Class. forName ("com. mysql. jdbc. driver "); con = DriverManager. getConnection ("jdbc: mysql: // 127.0.0.1: 3306/mydb", "root", "root"); stm = con. createStatement (); rs = cmd.exe cuteQuery ("select * from emp"); while (rs. next () {String name = rs. getString ("ename "); Int no = rs. getInt ("empno"); Date date = rs. getDate ("hiredate"); System. out. println (name + "" + no + "" + date) ;}} catch (ClassNotFoundException e) {e. printStackTrace (); throw new RuntimeException ("failed to load the driver");} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("SQL operation failed");} finally {try {if (rs! = Null) rs. close ();} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close rs");} try {if (stm! = Null) stm. close ();} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close stm");} try {if (con! = Null) con. close () ;}catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close con ");}}}}

9. Optimize the above Code (1)

Public class Test4 {@ Test public void jdbcTest () {// is defined outside, and the exception handling method is defined outside String driver = "com. mysql. jdbc. driver "; String url =" jdbc: mysql: // 127.0.0.1: 3306/mydb "; String username =" root "; String password =" root "; Connection con = null; statement stm = null; ResultSet rs = null; try {Class. forName (driver); con = DriverManager. getConnection (url, username, password); stm = con. createStatement (); Rs = cmd.exe cuteQuery ("select * from emp"); while (rs. next () {String name = rs. getString ("ename"); int no = rs. getInt ("empno"); Date date = rs. getDate ("hiredate"); System. out. println (name + "" + no + "" + date) ;}} catch (ClassNotFoundException e) {e. printStackTrace (); throw new RuntimeException ("failed to load the driver");} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("SQL operation failed ");} Finally {closeResultSet (rs); closeStatment (stm); closeConnection (con );}} // close Connection // close the Statement // close the ResultSet method public void closeConnection (Connection con) {try {if (con! = Null) con. close ();} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close con") ;}} public void closeStatment (Statement stm) {try {if (stm! = Null) stm. close ();} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close stm") ;}} public void closeResultSet (ResultSet rs) {try {if (rs! = Null) rs. close () ;}catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close rs ");}}}

10 optimization for the above Code

10.1 define a mysqldb. properties configuration file

Define configuration variables

driver=com.mysql.jdbc.Driverurl=jdbc\:mysql\://127.0.0.1\:3306/testguestusername=rootpassword=1234abcd

10.2 create jdbcUtil tool class JdbcUtil. cs

Get the value in the configuration file

Private static String driver; private static String url; private static String username; private static String password; // pair driver, url, username, the password value is static {// obtain the resource through the class loader and operate InputStream is = JdbcUtil in the stream mode. class. getClassLoader (). getResourceAsStream ("package name/db. properties "); Properties prop = new Properties (); try {prop. load (is); driver = prop. getProperty ("driver"); url = prop. getProperty ("url"); username = prop. getProperty ("username"); password = prop. getProperty ("password");} catch (IOException e) {e. printStackTrace (); throw new RuntimeException ("failed to read database configuration file ");}}

10.2.1 load driver

Static {try {Class. forName (driver);} catch (ClassNotFoundException e) {e. printStackTrace (); throw new RuntimeException ("failed to load the driver ");}}

10.2.2 how to obtain the connection

Public static Connection getConnection () {Connection con = null; try {con = DriverManager. getConnection (url, username, password);} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("database connection failed");} finally {} return con ;}

10.2.3 method of disabling

// Close Connection // close Statement // close the ResultSet method public static void close (Connection con) {try {if (con! = Null) con. close ();} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close con") ;}} public static void close (Statement stm) {try {if (stm! = Null) stm. close ();} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close stm") ;}} public static void close (ResultSet rs) {try {if (rs! = Null) rs. close ();} catch (SQLException e) {e. printStackTrace (); throw new RuntimeException ("failed to close rs ");}}

10.3 create a Test. CS class

public class Test {        @Test    public void select() {        Connection con = null;        Statement st = null;        ResultSet rs = null;        try {            con = JdbcUtil.getConnection();            st = con.createStatement();            rs = st.executeQuery("select * from tg_user");            while (rs.next()) {                System.out.println(rs.getInt(1));            }        } catch (SQLException e) {            e.printStackTrace();        } finally {            JdbcUtil.close(rs);            JdbcUtil.close(st);            JdbcUtil.close(con);        }    }}

 

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.