Application of data source in JDBC

zhaozj2021-02-16  105

The application profile of the data source in JDBC is well known that JDBC (Java Database Connections) is an important part of the Java 2 Enterprise Edition. It is an API based on the SQL layer. By embedding the SQL statement into a JDBC interface, the user can perform almost all database operations through the Java program. JDBC only provides an interface, and the specific class's implementation requires the database's designer to complete. By generating an example of these interfaces, even for different databases, the Java program can also perform SQL calls correctly. Therefore, for programmers, there is no need to put the attention to send SQL instructions to the database because the programmer needs to understand and use only JDBC interface, only in a very small number of cases, the class for a particular database, for example The programmer wants to use Oracle's extended API. In a JDBC program, you first need to do it to implement connections to the database. In the sample program, we use the Oracle8i JDBC package. Connecting the database usually requires the following steps: 1. Register the Database Driver (Driver). You can explicitly register the driver by calling the Java.sql.DriverManager class Register driver, or you can implicitly registering the driver by loading the database driver class. For example, we want to register Oracle8i JDBC driver // explicitly register DriverManager.RegisterDriver ("Oracle.jdbc.driver.Driver (" Oracle.jdbc.Driver.Driver.driver); // ImplicitDriver ()); // ); About how virtual machines automatically register with the database driver loaded by the class loader (ClassLoader) exceeds the scope discussed herein, do not make a detailed discussion. 2. establish connection. Call the java.sql.driverManager class getConnection () method can establish a connection to the database. The getConnection () method returns a Connection object. It should be noted that the getConnection () method automatically selects a most suitable driver from the Database Driver Registry. 3. Once the connection is established, AutoCommit is allowed. Call the serautocommit () method of the java.sql.connection interface can set whether the database is updated immediately after the program issues a SQL instruction to the database. Here is a specific example. In this example, the URL of the getConnection () method parameter is used is NET8 Keyword-Value PAIR format. Of course, it can also use ordinary formats. The database installed on the server named Chicago, the protocol used is the TCP protocol. The port used is 1521. The SID of the database is ChiDB, and the database driver used is an Oracle JDBC Thin driver.

Import java.sql. *; // Initialization constant private static string url = "JDBC: Oracle: Thin: @ (description = (Host = Chicago)" "(PROT = 1521))) Connect_data = (sID = chidb)) "; // can also set URL as" JDBC: Oracle: Thin: @ chicago: 1521: chidb "private static string username =" guest "; private static string password =" guest " Try {// Register the database class.forname ("Oracle.jdbc.driver.Driver.Oracledriver); // Establish connection connection conn = drivermanager.getConnection (URL, Username, Password); // Allow automatic update conn.setautoCommit (True );} catch (ClassNotFoundException E) {E.PrintStackTrace ();} catch (sqlexception e) {E.PrintStackTrace ();} From the perspective of practical applications, we can see that it is connected to the data inventory in this way. problem. The first is safety issues, because the program code contains username and password, others can get the username and password by the anti-compilation tool. The second is the portability problem of the code. If you want to connect the database name or user name to change, the programmer needs to modify the source, and then send the modified program to the user. That is, the software cannot be separated from the database independently. This will not only improve the cost of software, but also not conducive to the development of the software itself. This may also happen: In some cases, agency providing data does not want the database username and password to let the programmer of the program know. This puts forward a problem that hides some sensitive information when connecting Java and databases. Data Source and JNDI Data Sources are a concept introduced in JDBC 2.0. This concept is defined in the JDBC 2.0 extension package to describe this concept. If the user wants to create a database connection, you can get the corresponding database connection from the data source by querying the data source in the JNDI service. This way users only need to provide a logic name, not the specific details of the database login. It is necessary to briefly introduce JNDI here. JNDI's full name is Java Naming and Directory Interface, which is understood as a Java name and a directory service interface. JNDI provides an application with a mechanism for querying and using remote services. These services can be any business service. For JDBC applications, JNDI provides database connection services. Of course, JNDI can also provide other services to the database, but this is beyond the scope of this article, which is not discussed here. In fact, JNDI is not difficult to understand. Simply, the name service provides a mechanism for mapping an entity such as a file, a printer, a server, a logical name. For example, the name service in the operating system maps the printer to an I / O port. The directory service can be understood as an extension of the name service, which allows you to have your own properties in the service. Taking the printer as an example, the printer can be a color printer, supporting double-sided printing, supporting network printing, high-speed printing, etc. All of these printers can be stored in the directory service, and the corresponding printer is linked.

Some common directory services have NIS, NIS , LDAP, and Novell NDS. JNDI enables the application to obtain the services provided by the object and objects using the logical name, so that the programmer can avoid using the code associated with the organization that provides an object. For example, in the following example, the data source in JNDI is used, and the programmer does not need to provide the name of the Oracle8i driver, so that the transplantability of the code is stronger. Let's take a detail the data source and javax.sql.datasource interface. All information for establishing database connections is stored in the data source. As you can find a file in the file system by specifying the file name, you can find the appropriate database connection by providing the correct data source name. The Javax.sql.DataSource interface defines how to implement the data source. Nine properties are defined in this interface. Table 1 lists a description of these attributes. Since this paper is Oracle8i as an example, the ROLLENAME attribute is not implemented in Oracle8i, so there is no description of this attribute in the table. Table 1: Data Source Standard Properties Name Properties Data Type Description DatabaseName String Database Name, the SID of the database. DataSourceName String Data Source Interface Implementation The name of the class. Description String Description of the data source. NetworkProtocol String and server communication using the network protocol name. In Oracle8i, this property is only valid when using an OCI driver, the default protocol is a TCP protocol. Password string user login password. The port used by the PortNumber int database server, the default is 1521. ServerName String Database Server Name. User String User Login Name. The following methods are defined in the interface javax.sql.DataSource: * public synchronized void setDatabaseName (String dbname) * public synchronized String getDatabaseName () * public synchronized void setDataSourceName (String dsname) * public synchronized String getDataSourceName () * public synchronized void setDescription (String desc) * public synchronized String getDescription () * public synchronized void setNetworkProtocol (String np) * public synchronized String getNetworkProtocol () * public synchronized void setPassword (String pwd) * public synchronized void setPortNumber (int pn) * public synchronized int getPortNumber () * public synchronized void setServerName (String sn) * public synchronized String getServerName () * public synchronized void setUser (String user) * public synchronized String getUser () by these methods, programmers can get all the information to establish the required connection. It should be noted that the programmer does not get the login password, which guarantees security to a certain extent. Another point to note is that all methods are Synchronized methods, which is to ensure the thread security of the application (Thread-Safe).

If this method is called, even if the data source instance changes, it does not affect the correct operation of the program. In addition to achieving properties and methods defined by Sun, Oracle8i also provides its own data source properties and methods. These methods and properties are implemented in Oracle.jdbc.Pool.OracleDataSource. Oracle8i extended data source properties As shown in Table 2: Table 2: Property Name Properties Data Type Description Drivertype String Type of Oracle JDBC drivers used, including OCI8, Thin, and Kprb URL String database connections. tnsEntry String TNS oracle.jdbc.pool.OracleDataSource the entry name in addition to the methods defined by the interface implemented javax.sql.DataSource, also implements the following methods: * public synchronized void setDriverType (String dt) * public synchronized String getDriverType () * public synchronized void setURL (String url) * public synchronized String getURL () * public synchronized void setTNSEntryName (String tns) * public synchronized String getTNSEntryName () at the same time, OracleDataSource also achieved java.io.Serializable interfaces and javax.naming.Referenceable . Independent use of data source actual applications, you can register OracleDataSource to JNDI, or you can use it alone. Let's give an example of using OracleDataSource: // Initialization Data Source Instance OracleDataSource ODS = New OracleDataSource (); ODS.SETDRIVERTYPE ("Thin"); ods.setservername ("chicago"); ODS.setNetworkProtocol ("TCP"); ods.setNetworkProtocol ); ODS.SetDatabaseName ("chidb"); ODS.SETPORTNUMBER (1521); ODS.SETUSER ("Guest"); ods.setpassword ("guest"); // Get database connection CONN = ODS from the data source. GetConnection (); // Data operation through database connection ......................................................................................................................... Kprb, all other attributes have failed. If you use Thin or an OCI driver: URL can include a user login name and a user login password. For example: JDBC: Oracle: Thin: guest / guest @ Chicago: 1521: Chidb; If you set up URL properties, TNSENTRY, DRIVERTYPE, PortNumber, NetworkProtocol, ServerName, and DatabaseName properties will be invalid. In the case where the URL property is not set, if the Tnsentry property, PortNumber, NetworkProtocol, ServerName, and DatabaseName properties will be invalid if the TNSEntry property is set.

If you use an OCI driver, and the NetworkProtocol property is set to IPC, all other attributes outside user and password will be invalid. The use of the data source through JNDI first gives an actual program first, then explains how to query the data source through the JNDI.

Import java.sql. *; import javax.sql. *; import oracle.jdbc.driver. *; import oracle.jdbc.pool.racleDataSource; import javax.naming. *; import javax.naming.spi. *; import java .util.Hashtable; public class DataSourceJNDI {public static void main (String args []) throws SQLException {// initialization name service environment Context ctx = null; try {Hashtable env = new Hashtable (5); env.put (Context. INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); env.put (Context.PROVIDER_URL, "file: JNDI"); ctx = new InitialContext (env);} catch (NamingException ne) {ne.printStackTrace () ;} bind (ctx, "jdbc / chidb"); lookup (ctx, "jdbc / chidb");} static void bind (Context ctx, String ln) throws NamingException, SQLException {// create an instance of OracleDataSource ods = new OracleDataSource OracleDataSource (); ODS.SETDRIVERTYPE ("Thin"); ods.setservername ("chicago"); ODS.setNetworkProtocol ("TCP"); ODS.SetDatabaseName ("chidb"); ODS.SETPORTNUMBER (1521); ods.setuser ("guest"); ods.setpassword ("guest"); // Register the OracleDataSource instance to system.out.println in JNDI ("DOING A Bind Wit h the logical name: " ln); CTX.bind (ln, ods); System.out.Println (" SuccessFully Bound ");} static void lookup (Context CTX, String Ln) throws namingexception, sqlexception {// examples of the JNDI lookup OracleDataSource System.out.println ( "Doing a lookup with the logical name:" ln); OracleDataSource ods = (OracleDataSource) ctx.lookup (ln); System.out.println ( "Successful lookup"); // Get the database connection connection conn = ODS.GetConnection (); // in the inquiry OracleDataSource instance instance (); // closes connect (); conn = null;

转载请注明原文地址:https://www.9cbs.com/read-10956.html

New Post(0)