01. Get started with JDBC and basic knowledge about stocks

Source: Internet
Author: User

01. Get started with JDBC and basic knowledge about stocks
Reprinted please indicate the source: http://blog.csdn.net/u012637501
I. Getting started with JDBC1. JDBC IntroductionJDBC is Java Database Connectivity. JDBC provides a standard API for tools/Database developers to write Database applications using pure Java APIs. Java database programming interfaces are interfaces and classes in a set of standard Java languages,Java client programs can access different types of databasesFor example, you can create a database connection and execute SQL statements to access data. The JDBC specification adopts the idea of interface and implementation separation to design the Java database programming framework. Interfaces are included in the java. SQL and javax. SQL packages. java. SQL belongs to JavaSE and javax. SQL belongs to JavaEE. The implementation classes of these interfaces are called database drivers, which are provided by the database vendor or other vendor or individual. To make the client program independent from a specific database driver, we recommend that developers use an interface-based programming method in the JDBC specification, that is, to make the application only dependent on java. SQL and javax. SQL interfaces and classes.
2. JDBC driverJDBC drivers (Implementation classes for accessing database programming interfaces) are JDBC implementation classes created by database manufacturers according to JDBC specifications. JDBC class structure: ◆ DriverManager: is an implementation class, which is a factory class (the structure design mode of the class is the factory method), used to produce the database Driver object; ◆ Driver: the interface of the driver object. It points to a real database driver object. The database object obtains the driver object by calling the getDriver (String URL) of DriverManager, this method is implemented statically in the classes in the database driver package designed by each database vendor according to JDBC specifications; ◆ Connection: the object connected to the database is implemented through this interface, obtained through the getConnection (String URL) method of the DriverManager factory; ◆ Statement: interface used to execute static SQL statements, obtained through the createStatement method in the Connection ◆ Resultset: this interface is used to point to the result set object. The result set object is obtained through the execute method in Statement.
2. Steps for Java to access the database using JDBCCreate a program to connect to the database using JDBC, which contains seven steps:1. Load the database driver to JVMBefore connecting to the database, load the driver of the database to be connected to JVM (java Virtual Machine. lang. the static method forName (String className) of the Class is implemented. After Successful loading, the Driver Class instance is registered to the DriverManager Class. For example:

  1. Try {
  2. // Load the MySql Driver Class
  3. Class. forName ("com. mysql. jdbc. Driver ");
  4. } Catch (ClassNotFoundException e ){
  5. System. out. println ("The driver class cannot be found. Failed to load the driver! ");
  6. E. printStackTrace ();
  7. }
Note: com. mysql. jdbc. Driver is the MySQL database Driver class, located in the mysql-connector-java-3.1.11-bin.jar com. mysql. jdbc package Driver. class (class ). 2. Provide the URL of the JDBC connectionThe connection URL defines the protocol, sub-protocol, and data source identification used to connect to the database. Writing format: Protocol: Sub-Protocol: Data Source Identification Protocol: Always starting with JDBC in jdbc; Sub-Protocol: the name of the Bridge Connection driver or database management system; data source identification: mark the address and connection port of the database source. For example: (MySql connection URL) jdbc: mysql: // localhost: 3306/test? UseUnicode = true & characterEncoding = gbk;
Here, test is the database name; 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 is the character encoding method. 3. Create a database connectionTo connect to the database, you need to request to java. SQL. DriverManager and obtain the Connection object. This object represents the Connection to a database. Use the getConnectin (String url, String username, String password) method of DriverManager to input the path of the database to be connected, and the username and password of the database. For example:
  1. // Connect to the MySql database. Both the user name and password are root.
  2. String url = "jdbc: mysql: // localhost: 3306/test ";
  3. String username = "root ";
  4. String password = "root ";
  5. Try {
  6. Connection con =
  7. DriverManager. getConnection (url, username, password );
  8. } Catch (SQLException se ){
  9. System. out. println ("database connection failed! ");
  10. Se. printStackTrace ();
  11. }
4. Create a StatementTo execute an SQL statement, you must obtain the java. SQL. statement instances are divided into three types: (1) execute static SQL statements, which are usually implemented through the Statement instance; (2) execute dynamic SQL statements, which are usually implemented through the PreparedStatement instance; (3) execute the database Stored Procedure, usually through the CallableStatement instance. Specific implementation methods:
  1. Statement stmt = con. createStatement (); // execute a static SQL Statement
  2. PreparedStatement pstmt = con. prepareStatement (SQL); // execute dynamic SQL statements
  3. CallableStatement cstmt = con. prepareCall ("{CALL demoSp (? ,?)} "); // Execute the Stored Procedure
5. Execute SQL statementsThe Statement interface provides three methods to execute SQL statements: executeQuery, executeUpdate, and execute (1) ResultSet executeQuery (String sqlString): execute the SQL Statement to query the database and return a result set (ResultSet) (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 ): it is used to execute statements that return multiple result sets, multiple update counts, or a combination of the two. Specific implementation code:
  1. ResultSet rs = stmt.exe cuteQuery ("SELECT * FROM ...");
  2. Int rows = stmt.exe cuteUpdate ("insert ...");
  3. Boolean flag = stmt.exe cute (String SQL );
6. processing resultTwo 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. • ResultSet contains all rows that meet the conditions in the SQL statement, and it provides access to the data in these rows through a set of get Methods: • Use the ResultSet) object Access Method to obtain data:
  1. While (rs. next () {// The returned result set is a series of row (record) data.
  2. String name = rs. getString ("name ");
  3. String pass = rs. getString (1); // This method is more efficient.
  4. } (Columns are numbered from left to right and start from column 1)
7. Disable JDBC objectsAfter the operation is completed, all the used JDBC objects should be closed to release the JDBC resources. The order of closure is the opposite to the declared order: (1) closing the record set (2) closing the declaration (3) close connection object
  1. If (rs! = Null) {// close the record set
  2. Try {
  3. Rs. close ();
  4. } Catch (SQLException e ){
  5. E. printStackTrace ();
  6. }
  7. }
  8. If (stmt! = Null) {// close the Declaration
  9. Try {
  10. Stmt. close ();
  11. } Catch (SQLException e ){
  12. E. printStackTrace ();
  13. }
  14. }
  15. If (conn! = Null) {// close the connection object
  16. Try {
  17. Conn. close ();
  18. } Catch (SQLException e ){
  19. E. printStackTrace ();
  20. }
  21. }
Conclusion 1: loading different database drivers to JMV code (1) Oracle Database: Class. forName ("oracle. jdbc. driver. oracleDriver "); (2) SQL Server database: Class. forName ("com. microsoft. jdbc. sqlserver. SQLServerDriver "); (3) MySQL database: Class. forName ("com. mysql. jdbc. driver "); (4) Access Database: Class. forName ("sun. jdbc. odbc. jdbcOdbcDriver "); Conclusion 2: Create a database Connection string in the format of Connection con = DriverManager. getConnection ("database jdbc url", "database username", "Database Password ");
3. Drivers and JDBC URLs of common databases 1. Oracle Database(1) driver package name: ojdbc14.jar (2) Name of the driver class: oracle. jdbc. driver. oracleDriver (3) jdbc url: jdbc: oracle: thin: @ dbip: port: databasename Description: The driver package name may change to the Black font part of the jdbc url, which must be kept intact, the URL format recognized by the driver. The red font must be filled in according to the database installation. The meaning of each part is as follows: dbip-the IP address of the database server. If it is a local IP address, it can be written as localhost or 127.0.0.1. Port-indicates the listening port of the database. You need to check the configuration during installation. The default value is 1521. Databasename-is the SID of the database, usually the name of the global database. For example, to access the local database allandb, port 1521, the URL is written as follows: jdbc: oracle: thin: @ localhost: 1521: allandb: http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html 2. SQL Server database(1) driver package name: msbase. jar mssqlserver. jar msutil. jar (2) Driver Class Name: com. microsoft. jdbc. sqlserver. SQLServerDriver (3) jdbc url: jdbc: microsoft: sqlserver: // dbip: port; DatabaseName = databasename description: the driver package name may change to the URL format recognized by the driver because the Black font in the jdbc url must be kept intact. The red font must be filled in according to the database installation. The meaning of each part is as follows: dbip-the IP address of the database server. If it is a local IP address, it can be written as localhost or 127.0.0.1. Port-indicates the listening port of the database. You need to check the configuration during installation. The default value is 1433. Databasename-database name. For example, to access the local database allandb, port 1433, the URL is written as follows: jdbc: microsoft: sqlserver: @ localhost: 1433; DatabaseName = allandb: http://www.microsoft.com/downloads/details.aspx 3. MySQL database(1) driver package name: mysql-connector-java-3.1.11-bin.jar (2) Name of the driver class: com. mysql. jdbc. driver (3) jdbc url: jdbc: mysql: // dbip: port/databasename Description: The Driver package name may change to the Black font part of the jdbc url, which must be kept intact, the URL format recognized by the driver. The red font must be filled in according to the database installation. The meaning of each part is as follows: dbip-the IP address of the database server. If it is a local IP address, it can be written as localhost or 127.0.0.1. Port-indicates the listening port of the database. You need to check the configuration during installation. The default value is 3306. Databasename-database name. For example, if you want to access the local database allandb, port 1433, then the URL is written as follows: jdbc: mysql: // localhost: 3306/allandb: http://dev.mysql.com/downloads/connector/j/ 4. Access Database(1) driver package name: this driver is included in JavaSE and does not require additional installation. (2) name of the driver class: sun. jdbc. odbc. jdbcOdbcDriver (3) jdbc url: jdbc: odbc: datasourcename Description: The driver can only work in Windows, first, you need to create a local data source (ODBC) that can Access the Access database in the operating system, if the name is allandb, then the URL is written as follows: jdbc: odbc: allandb reference http://www.cnblogs.com/lee/archive/2007/08/25/869656.htmlhttp://jingyan.baidu.com/article/5225f26b20b67ae6fa0908ba.htmlhttp://www.cnblogs.com/hongten/archive/2011/03/29/1998311.html

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.