- Ubuntu Documentation
- Installation
- Set up MySQL default password
- Create SQL Databases and tables
- User creation and privileges
- Eclipse
- Setting up the user to use JDBC
- Testing in Java
- 2 Getting Started
- Version Compatibility for Oracle JDBC Drivers
- Verifying a JDBC Client Installation
- Check the Installed Directories and Files
- Check the Environment Variables
- Ensure that the Java Code Can Be Compiled and Run
- Determine the Version of the JDBC Driver
- Test JDBC and the Database Connection
- Basic Steps in JDBC
- Importing Packages
- O pening a Connection to a Database
- Creating a Statement Object
- Running a Query and Retrieving a Result Set Object
- Processing the Result Set Object
- Closing the Result Set and Statement Objects
- Making Changes to the Database
- Com mitting Changes
- Changing Commit Behavior
- Working with Invisible Columns
- Closing the Connection
- Sample: Connecting, Querying, and Processing the Results
- Stored Procedure Calls in JDBC Programs
- PL/SQL Stored Procedures
- Java Stored Procedures
- Support for Implicit Results
- Processing SQL Exceptions
Ubuntu Documentation
For Ubuntu versions : 5.10, 6.06, 6.10, 7.04, 9.10
This document explains how to set up Java applications to communicate with the MySQL Database. This can be used either in Java development, or applications which use JDBC such as OpenOffice.Org. See Using MySQL, JDBC and OpenOffice for more information.
This document was written originally for 5.10, but has been updated for 6.06. Changes required for 5.10 are shown in italics
It has also been checked against 6.10 (Edgy Eft) and 7.04 (Feisty Fawn), which should be installed as for 6.06
Installation
Install mysql client, server and the jdbc connector, either via synaptic or by using the following
On 5.10 you may need select «No configuration» for postfix if it is installed.
Set up MySQL default password
Set up the password for the root user as ‘root’ or whatever you want. The last entry is the password
Check you can connect to mysql
then enter the password you just set and press return again. In this case it would be «root».
Create SQL Databases and tables
Create databases and tables or whatever, so you have some data to work with. You can disconnect and use mysql-query-browser for this if you wish. For the sample code below just enter
User creation and privileges
Create a user with access to that table. Replace the items in square brackets by the database name, and the chosen user and password. Don’t type in the square brackets !
Note: Ubuntu 5.10 requires localhost.localdomain
This is required because when you connect using «mysql -u root -p» it connects directly to the Sql Server. The «grant» line creates access via 127.0.0.1 (localhost). This is no longer an issue on 6.10.
You can test this by
This will work only for the user you have just «granted», not for root. Counter-intuitively, the ‘default’ server and localhost/127.0.0.1 aren’t the same thing
Eclipse
For those who are using Eclipse, you will likely to have a ‘Class Not Found’ exception. To fix this, go to: Project, click Properties, select Java Build Path, and choose the Libraries tab. Then select ‘Add External JARs’, and find ‘/usr/share/java/mysql-connector-java.jar’.
Setting up the user to use JDBC
Add these two lines to /home/[user]/.bashrc. I am running Java 5 which doesn’t require the current directory to be on the Classpath ; I *think* Java 2 does, but I’m not going back to check it In that case you may need to have $CLASSPATH. /user/share/java/mysql.jar
Alternatively, you can set it for all users, by editing /etc/environment (use sudo — sudo vi /etc/environment)
Log out and Log in again. (If you only edited /home/[user]/.bashrc you don’t need to log out/in, only execute in a terminal «$source .bashrc» in your home dir). Start up a terminal and type:
It should print out something like «:/usr/share/java/mysql.jar»
Testing in Java
It should now work. Here is some typical code (clearing up removed for simplicity)
JDBCAndMySQL (последним исправлял пользователь chengzhe-wu 2010-04-20 13:28:19)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Источник
2 Getting Started
This chapter discusses the compatibility of Oracle Java Database Connectivity (JDBC) driver versions, database versions, and Java Development Kit (JDK) versions. It also describes the basics of testing a client installation and configuration and running a simple application. This chapter contains the following sections:
Version Compatibility for Oracle JDBC Drivers
This section discusses the general JDBC version compatibility issues.
Oracle Database 12 c Release 1 (12.1) JDBC drivers are certified with supported Oracle Database releases (11.x.0.x). However, they are not certified to work with older, unsupported database releases, such as 10.2.x, 10.1.x, 9.2.x, and 9.0.1.x.
Existing and supported JDBC drivers are certified to work with Oracle Database 12 c Release 1 (12.1).
In Oracle Database 12 c Release 1 (12.1), Oracle JDBC drivers no longer support JDK 1.4.x or earlier versions.
Verifying a JDBC Client Installation
To verify a JDBC client installation, you must do all of the following:
This section describes the steps for verifying an Oracle client installation of the JDBC drivers, assuming that you have already installed the driver of your choice. Installation of an Oracle JDBC driver is platform-specific. You must follow the installation instructions for the driver you want to install in your platform-specific documentation.
If you use the JDBC Thin driver, then there is no additional installation on the client computer. If you use the JDBC Oracle Call Interface (OCI) driver, then you must also install the Oracle client software. This includes Oracle Net and the OCI libraries.
The JDBC Thin driver requires a TCP/IP listener to be running on the computer where the database is installed.
Check the Installed Directories and Files
Installing the Oracle Java products creates, among other things, the following directories:
Check whether or not the following directories and files have been created and populated in the ORACLE_HOME /jdbc directory:
This directory contains a compressed file, demo.zip or demo.tar . When you uncompress this compressed file, the samples directory and the Samples-Readme.txt file are created. The samples directory contains sample programs, including examples of how to use JDBC escape syntax and Oracle SQL syntax, PL/SQL blocks, streams, user-defined types, additional Oracle type extensions, and Oracle performance extensions.
This directory contains the javadoc.zip file, which is the Oracle JDBC application programming interface (API) documentation.
The lib directory contains the following required Java classes:
orai18n.jar and orai18n-mapping.jar
Contain classes for globalization and multibyte character sets support
ojdbc6.jar , ojdbc6_g.jar , ojdbc7.jar , and ojdbc7_g.jar
Contain the JDBC driver classes for use with JDK 6 and JDK 7
Since Oracle Database 11 g Release 1, support for a version of JDK earlier than version 5.0 has been removed. Also, the ojdbc14.jar , ojdbc5.jar and classes12.jar files are no longer shipped. Instead, you can use the ojdbc6.jar and ojdbc7.jar files, which are shipped with Oracle Database 12 c .
If you are using JSE 6 and later, then there is no need to explicitly load the JDBC driver. This means that the Java run-time loads the driver when needed and you need not include Class.forName(«oracle.jdbc.OracleDriver») or new oracle.jdbc.OracleDriver() in your code. But if you are using J2SE 5.0, then you need to load the JDBC driver explicitly.
This file contains late-breaking and release-specific information about the drivers, which may not have been included in other documentation on the product.
Check whether or not the following directories have been created and populated in the ORACLE_HOME /jlib directory:
jta.jar and jndi.jar
These files contain classes for the Java Transaction API (JTA) and the Java Naming and Directory Interface (JNDI). These are required only if you are using JTA features for distributed transaction management or JNDI features for naming services.
For more information about these files, visit the following sites
This JAR file contains classes for Oracle RAC Fast Application Notification. It is also required for Universal Connection Pool (UCP) features like Fast Connection Failover, Run-time Load Balancing, Web Session Affinity, and Transaction Affinity.
Check the Environment Variables
This section describes the environment variables that must be set for the JDBC OCI driver and the JDBC Thin driver, focusing on Solaris, Linux, and Microsoft Windows platforms.
You must set the CLASSPATH environment variable for JDBC OCI or Thin driver. Include the following in the CLASSPATH environment variable:
If you use the JTA features and the JNDI features, then you must specify jta.jar and jndi.jar in your CLASSPATH environment variable.
JDBC OCI Driver
To use the JDBC OCI driver, you must also set the following value for the library path environment variable:
On Solaris or Linux, set the LD_LIBRARY_PATH environment variable as follows:
This directory contains the libocijdbc11.so shared object library.
On Microsoft Windows, set the PATH environment variable as follows:
This directory contains the ocijdbc11.dll dynamic link library.
All of the JDBC OCI demonstration programs can be run in the Instant Client mode by including the JDBC OCI Instant Client data shared library on the library path environment variable.
JDBC Thin Driver
To use the JDBC Thin driver, you do not have to set any other environment variables. However, to use the JDBC server-side Thin driver, you need to set permission.
Setting Permission for the Server-Side Thin Driver
The JDBC server-side Thin driver opens a socket for its connection to the database. Because Oracle Database enforces the Java security model, a check is performed for a SocketPermission object.
To use the JDBC server-side Thin driver, the connecting user must be granted the appropriate permission. The following is an example of how the permission can be granted for the user HR :
Note that JDBCTHIN in the grant_permission call must be in uppercase. The asterisk ( * ) is a pattern. You can restrict the user by granting permission to connect to only specific computers or ports.
Ensure that the Java Code Can Be Compiled and Run
To further ensure that Java is set up properly on your client system, go to the samples directory under the ORACLE_HOME /jdbc/demo directory. Now, type the following commands on the command line, one after the other, to see if the Java compiler and the Java interpreter run without error:
Each of the preceding commands should display a list of options and parameters and then exit. Ideally, verify that you can compile and run a simple test program, such as jdbc/demo/samples/generic/SelectExample .
Determine the Version of the JDBC Driver
To determine the version of the JDBC driver, call the getDriverVersion method of the OracleDatabaseMetaData class as shown in the following sample code:
You can also determine the version of the JDBC driver by executing the following commands:
java -jar ojdbc6.jar
java -jar ojdbc7.jar
Test JDBC and the Database Connection
The samples directory contains sample programs for a particular Oracle JDBC driver. One of the programs, JdbcCheckup.java , is designed to test JDBC and the database connection. The program queries for the user name, password, and the name of the database to which you want to connect. The program connects to the database, queries for the string » Hello World «, and prints it to the screen.
Go to the samples directory, and compile and run the JdbcCheckup.java program. If the results of the query print without error, then your Java and JDBC installations are correct.
Although JdbcCheckup.java is a simple program, it demonstrates several important functions by performing the following:
Imports the necessary Java classes, including JDBC classes
Creates a DataSource instance
Connects to the database
Runs a simple query
Prints the query results to your screen
The JdbcCheckup.java program, which uses the JDBC OCI driver, is as follows:
Basic Steps in JDBC
After verifying the JDBC client installation, you can start creating your JDBC applications. When using Oracle JDBC drivers, you must include certain driver-specific information in your programs. This section describes, in the form of a tutorial, where and how to add the information. The tutorial guides you through the steps to create code that connects to and queries a database from the client.
You must write code to perform the following tasks:
You must supply Oracle driver-specific information for the first three tasks that enable your program to use the JDBC application programming interface (API) to access a database. For the other tasks, you can use standard JDBC Java code, as you would for any Java application.
Importing Packages
Regardless of which Oracle JDBC driver you use, include the import statements shown in Table 2-1 at the beginning of your program.
Table 2-1 Import Statements for JDBC Driver
Import statement | Provides | ||||||||
---|---|---|---|---|---|---|---|---|---|
Operation | Error Messages | ||||||
---|---|---|---|---|---|---|---|
Method | Description |
---|---|
getMoreResults | Checks if there are more results available in the result set |
getMoreResults(int) | Checks if there are more results available in the result set, like the overloaded method. This method accepts an int parameter that can have one of the following values: |
getResultSet | Iteratively retrieves each implicit result from an executed PL/SQL statement |
The server-side internal driver, kprb does not support fetching information about implicit results.
Only SELECT queries can be returned implicitly.
Applications retrieve each result set sequentially, but can fetch rows from any result set independent of the sequence.
Suppose you have a procedure called foo as the following:
The following code snippet demonstrates how to retrieve the implicit results returned by PL/SQL procedures using the getMoreResults methods:
Suppose you have another procedure called foo as the following:
The following code snippet demonstrates how to retrieve the implicit results returned by PL/SQL procedures using the getMoreResults(int) methods:
Processing SQL Exceptions
To handle error conditions, Oracle JDBC drivers throw SQL exceptions, producing instances of the java.sql.SQLException class or its subclass. Errors can originate either in the JDBC driver or in the database itself. Resulting messages describe the error and identify the method that threw the error. Additional run-time information can also be appended.
JDBC 3.0 defines only a single exception, SQLException . However, there are large categories of errors and it is useful to distinguish them. Therefore, in JDBC 4.0, a set of subclasses of the SQLException exception is introduced to identify the different categories of errors. To know more about this feature, see Support for JDBC 4.0 Standard.
Basic exception handling can include retrieving the error message, retrieving the error code, retrieving the SQL state, and printing the stack trace. The SQLException class includes functionality to retrieve all of this information, when available.
Retrieving Error Information
You can retrieve basic error information with the following methods of the SQLException class:
The following example prints output from a getMessage method call:
This would print the output, such as the following, for an error originating in the JDBC driver:
Error message text is available in alternative languages and character sets supported by Oracle.
Printing the Stack Trace
The SQLException class provides the printStackTrace() method for printing a stack trace. This method prints the stack trace of the Throwable object to the standard error stream. You can also specify a java.io.PrintStream object or java.io.PrintWriter object for output.
The following code fragment illustrates how you can catch SQL exceptions and print the stack trace.
To illustrate how the JDBC drivers handle errors, assume the following code uses an incorrect column index:
Assuming the column index is incorrect, running the program would produce the following error text:
Источник