JDBC Connection Database Experience Collection

Source: Internet
Author: User
Tags execution connect odbc sql mysql string sybase oracle database
Connecting to a database Java database connection (JDBC) consists of a set of classes and interfaces written in the Java programming language. JDBC provides tools/database developers with a standard API that enables them to write database applications with a pure Java API. However, each developer's interface is not exactly the same, so the development environment changes will bring a certain configuration changes. This article mainly sets up the connection ways of different databases.

   One, connect various database way quick look-up table

The following is a list of how the various databases use JDBC connections and can be used as a manual.

1, oracle8/8i/9i database (thin mode)

Class.forName ("Oracle.jdbc.driver.OracleDriver"). newinstance ();
String url= "Jdbc:oracle:thin: @localhost: 1521:ORCL"; ORCL is the SID of the database
String user= "Test";
String password= "Test";
Connection conn= drivermanager.getconnection (Url,user,password);

2. DB2 Database

Class.forName ("Com.ibm.db2.jdbc.app.DB2Driver"). newinstance ();
String url= "Jdbc:db2://localhost:5000/sample"; Sample for your database name
String user= "admin";
String password= "";
Connection conn= drivermanager.getconnection (Url,user,password);

3. SQL server7.0/2000 Database

Class.forName ("Com.microsoft.jdbc.sqlserver.SQLServerDriver"). newinstance ();
String url= "Jdbc:microsoft:sqlserver://localhost:1433;databasename=mydb";
MyDB as a database
String user= "SA";
String password= "";
Connection conn= drivermanager.getconnection (Url,user,password);

4. Sybase database

Class.forName ("Com.sybase.jdbc.SybDriver"). newinstance ();
String url = "Jdbc:sybase:tds:localhost:5007/mydb";//mydb for your database name
Properties sysprops = System.getproperties ();
Sysprops.put ("User", "userid");
Sysprops.put ("Password", "User_password");
Connection conn= drivermanager.getconnection (URL, sysprops);

5. Informix Database

Class.forName ("Com.informix.jdbc.IfxDriver"). newinstance ();
String url = "Jdbc:informix-sqli://;
User=testuser;password=testpassword "; MyDB for Database name
Connection conn= drivermanager.getconnection (URL);

6. mysql Database

Class.forName ("Org.gjt.mm.mysql.Driver"). newinstance ();
String url = "jdbc:mysql://localhost/mydb?user=soft&password=soft1234&useunicode=true& Characterencoding=8859_1 "
MyDB for Database name
Connection conn= drivermanager.getconnection (URL);

7. PostgreSQL Database

Class.forName ("Org.postgresql.Driver"). newinstance ();
String url = "Jdbc:postgresql://localhost/mydb"//mydb for database name
String user= "MyUser";
String password= "MyPassword";
Connection conn= drivermanager.getconnection (Url,user,password);

8, Access database directly with the ODBC

Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
String url= "Jdbc:odbc:driver={microsoft Access Driver (*.mdb)};D bq=" +application.getrealpath ("/data/reportdemo.mdb ");
Connection conn = drivermanager.getconnection (URL, "", "");
Statement stmtnew=conn.createstatement ();

   two, JDBC connection MySQL way

Here's a little tutorial on using JDBC to connect to MySQL

1. Find the driver

MySQL currently offers Java drivers for connection/j, which can be downloaded from the MySQL official website, and locate the Mysql-connector-java-3.0.15-ga-bin.jar file, which is a pure Java driver and does not require additional configuration.

2, dynamic designation Classpath

If you need to dynamically specify CLASSPATH when executing, use the-CP method at execution time. Otherwise, add the. jar file above to the CLASSPATH environment variable.

3. Load Driver

Class.forName (Com.mysql.jdbc.Driver);
System.out.println (Success loading Mysql driver!);
}catch (Exception e)
System.out.println (Error loading Mysql driver!);
E.printstacktrace ();

4, set the URL of the connection


   Three, here are some tips for using JDBC to connect to an Oracle database

These techniques enable us to better perform system performance and achieve more functionality.

1, use the thin driver in the client software development

In the development of Java software, Oracle's database provides four types of drivers, two for application software, applets, Servlets and other client software, and two for the Java stored procedures in the database and other server-side software. In the development of client side software, we can choose OCI driver or thin driver. The OCI driver uses the Java Localization Interface (JNI) to communicate with the database through Oracle client software. The thin driver is a pure Java driver that communicates directly with the database. For maximum performance, Oracle recommends using the OCI driver in the development of the client software, which seems to be correct. However, I recommend using the thin driver because multiple tests have found that, in general, the performance of the thin driver exceeds the OCI driver.

2, turn off the automatic submission function, improve system performance

When you first establish a connection to a database, by default, the connection is in autocommit mode. For better performance, you can turn off the autocommit feature by calling the Setautocommit () method of the connection class with the Boolean false parameter, as follows:

Conn.setautocommit (FALSE);

It is noteworthy that once the autocommit feature is turned off, we need to manage the transaction manually by invoking the commit () and rollback () Methods of the connection class.

3. Use the Statement object in dynamic SQL or time constrained commands

When executing SQL commands, we have two choices: you can use the PreparedStatement object, or you can use the statement object. No matter how many times the same SQL command is used, PreparedStatement only parses and compiles it once. When the statement object is used, it is parsed and compiled each time an SQL command is executed. This may make you think that using a PreparedStatement object is faster than using a statement object. However, the tests I conducted showed that this was not the case in the client software. Therefore, in a time-constrained SQL operation, we should consider using the statement object, unless the SQL commands are processed in batches.

Also, using the statement object makes it easier to write dynamic SQL commands because we can concatenate strings together to create a valid SQL command. Therefore, I think the statement object makes it easier to create and execute dynamic SQL commands.

4. Use helper function to format dynamic SQL commands

When creating dynamic SQL commands that are executed using the statement object, we need to deal with some formatting problems. For example, if we want to create an SQL command that inserts the name O ' Reilly into the table, you must replace the "'" Number in O ' Reilly with a two-connected "" number. The best way to do this is to create a helper method that completes the substitution operation, and then use the helper method that is created when the connection string expresses an SQL command in the heart-taking formula. Similarly, we can have the helper method accept a date-type value and then let it output a string expression based on the Oracle To_date () function.

5, using PreparedStatement object to improve the overall efficiency of the database

When the SQL command is executed using the PreparedStatement object, the command is parsed and compiled by the database and then placed in the command buffer. Then, whenever the same PreparedStatement object is executed, it is parsed again, but it is not compiled again. Precompiled commands can be found in the buffer and can be reused. In enterprise-class applications with a large number of users, the same SQL commands are often executed repeatedly, and the reduction in compilation times with PreparedStatement objects can improve the overall performance of the database. If it takes longer than the statement task to create, prepare, and perform preparedstatement tasks on the client, I recommend that you use the PreparedStatement object in all cases except the dynamic SQL command.

6. Use the PreparedStatement object in a batch process duplicate insert or update operation

If you process inserts and updates in batches, you can significantly reduce the time they need. The statement and CallableStatement provided by Oracle do not really support batching, and only PreparedStatement objects truly support batch processing. We can use the Addbatch () and ExecuteBatch () methods to select standard JDBC batches, or by using the Setexecutebatch () method of the PreparedStatement object and the standard executeupdate () method to choose a faster Oracle proprietary approach. To use the Oracle proprietary batch mechanism, you can invoke Setexecutebatch () in the manner shown below:

PreparedStatement Pstmt3d null;
try {
((oraclepreparedstatement) pstmt). Setexecutebatch (30);
Pstmt.executeupdate ();

The value specified when calling Setexecutebatch () is an upper bound, and when that value is reached, SQL command execution is automatically raised, and the standard Executeupdate () method is sent as a batch to the database. We can transfer batch tasks at any time by invoking the Sendbatch () method of the PreparedStatement class.

7. Insert and update large objects (LOB) using Oracle Locator method

Oracle's PreparedStatement classes do not fully support the processing of large objects such as blobs and clob, especially thin drivers do not support SetObject () and Setbinarystream using PreparedStatement objects () method to set the value of a blob, nor does it support the use of the Setcharacterstream () method to set CLOB values. Only the method in the locator itself can get the value of the LOB type from the database. You can use the PreparedStatement object to insert or update the LOB, but you need to use locator to get the value of the LOB. Because of these two problems, I recommend using the Locator method to insert, update, or get LOB values.

8. Using SQL92 syntax to invoke stored procedures

When invoking a stored procedure, we can use SQL92 or Oracle Pl/sql, because there is no real benefit from using Oracle Pl/sql, and it can cause problems for future developers who maintain your application, so I recommend using SQL92 when calling stored procedures.

9, using object SQL to transfer the objects mode to the database

Since Oracle's databases can be used as an object-oriented database, you can consider going to the database for object-oriented patterns in your application. The current approach is to create Java beans as camouflaged database objects, map their properties to relational tables, and then add methods to those beans. Although this is not a problem in Java, because operations are performed outside the database, other applications that access the database cannot take advantage of object patterns. If you take advantage of Oracle's object-oriented technology, you can emulate its data and operations in a database by creating a new database object type, and then generate your own Java bean classes using tools such as Jpublisher. In this way, not only can Java applications use the object schema of the application software, but other applications that need to share data and operations in your application can also use object patterns in the application software.

10, the use of SQL to complete the operation of the database

The most important experience I want to introduce to you is to take full advantage of SQL's collection-oriented approach to database processing requirements, rather than using procedural programming languages such as Java.

If a programmer wants to find many rows in a table, each row in the result looks for data from another table, and finally, the programmer creates a separate update command to batch update the data in the first table. Tasks similar to this can be done in an update command by using a multiple-column subquery in the SET clause. When you can complete a task in a single SQL command, why should you let the data flow over the Internet? I recommend that users carefully learn how to maximize the functionality of SQL.

Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.