Vous êtes sur la page 1sur 12

If you want to know the database server name and version, or the JDBC driver name and version,

you can get them through the DatabaseMetaData object as shown in t he following sample program: /** * OdbcSqlServerDatabaseInfo.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class OdbcSqlServerDatabaseInfo { public static void main(String [] args) { Connection con = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection( "jdbc:odbc:SQL_SERVER;user=sa;password=HerongYang"); // Database and driver info DatabaseMetaData meta = con.getMetaData(); System.out.println("Server name: " + meta.getDatabaseProductName()); System.out.println("Server version: " + meta.getDatabaseProductVersion()); System.out.println("Driver name: " + meta.getDriverName()); System.out.println("Driver version: " + meta.getDriverVersion()); System.out.println("JDBC major version: " + meta.getJDBCMajorVersion()); System.out.println("JDBC minor version: " + meta.getJDBCMinorVersion()); con.close(); } catch (Exception e) { System.err.println("Exception: "+e.getMessage()); } } } I got the following output from this program: Server name: Microsoft SQL Server Server version: 09.00.1399 Driver name: JDBC-ODBC Bridge (SQLSRV32.DLL) Driver version: 2.0001 (03.85.1117) JDBC major version: 2 JDBC minor version: 0 The output confirms that the version the my SQL Server is 09.00.1399 (2005).

Downloading and Installing Java DB (Derby) This section describes how to download and install Java DB (Derby) 10.2.2 - free for evaluation. Java DB is a relational database management system that is based on the Java pro gramming language and SQL. Java DB is a commercial release of the Apache Softwar e Foundation's (ASF) open source relational database project. But you can still

download a copy of Java DB free for evaluation. The Apache project is called Der by. You can download and install a copy of Java DB 10.2.2 free for evaluation as sho wn in this tutorial: Go to http://developers.sun.com/javadb/, the Java DB home page. Cick the Downloads tab. Click the Download link next to Java DB 10.2.2. Click the Download link. Register yourself. Check the checkbox to accept the terms Click "Windows self-extracting file" next to English - javadb-10_2_2_0-windo ws.exe 9.71 MB to start download Java DB. Save the download file, javadb-10_2_2_0-windows.exe to \local Double click \local\javadb-10_2_2_0-windows.exe to start unpacking the Java DB. Now I have Java DB installed in directory: \local\javadb. No need to run any ins tallation program.

This section describes how to use 'sysinfo' to verify Java DB installation. Obviously, Java DB requires Java SE to be installed. I have Java SE 6 installed on my Windows system as described in other tutorials in this book. To verify Jav a DB installation and the required Java SE, I used the "sysinfo" tool as suggest ed in Java DB documents: C:\>cd \local\javadb\bin C:\local\javadb\bin>sysinfo ------------------ Java Information -----------------Java Version: 1.6.0_02 Java Vendor: Sun Microsystems Inc. Java home: C:\progra~1\java\jdk1.6.0_02\jre Java classpath: C:\local\javadb\bin\../lib/derby.jar; C:\local\javadb\bin\../lib/derbynet.jar; C:\local\javadb\bin\../lib/derbyclient.jar; C:\local\javadb\bin\../lib/derbytools.jar OS name: Windows XP OS architecture: x86 OS version: 5.1 Java user name: herong Java user home: C:\Documents and Settings\herong Java user dir: C:\home\herong java.specification.name: Java Platform API Specification java.specification.version: 1.6 --------- Derby Information -------JRE - JDBC: Java SE 6 - JDBC 4.0 [C:\local\javadb\lib\derby.jar] 10.2.2.0 - (485682) [C:\local\javadb\lib\derbytools.jar] 10.2.2.0 - (485682) [C:\local\javadb\lib\derbynet.jar] 10.2.2.0 - (485682) [C:\local\javadb\lib\derbyclient.jar] 10.2.2.0 - (485682) ... The output confirms that my Java DB was installed properly.

Setting Up Java DB (Derby) in Network Server This section describes how to set up and run Java DB in Network Server mode list ening client connections over the network. Java DB can be used in two modes: Embedded Mode - The database will be started and executed as part of a Java application, sharing the same JVM as the application. Network Server - The database will be started as a stand alone application a nd listening client connections over the network on a TCP/IP port. I want to try the Network Server mode first. Here is what I did to setup Java DB and start it in Network Server mode: C:\>cd \local\javadb C:\local\javadb>mkdir databases C:\local\javadb>cd databasess C:\local\javadb\databases>..\bin\startNetworkServer.bat Apache Derby Network Server - 10.2.2.0 - (485682) started and ready to accept connections on port 1527 at 2007-08-15 17:20:39.640 GMT Cool. My Java DB is up and running in Network Server mode on host "localhost" an d listening connections on port "1527". Note that I created a new directory called C:\local\javadb\databases and started Java DB from this directory. In this way, C:\local\javadb\databases will be use d as the database home directory. Any new databases created on Java DB server wi ll be located in this directory.

This section describes how to use the command line tool 'ij' to create a new dat abase with a new table. "ij" is a command line client tool included in the Java DB package. You can use "ij" to run any SQL statements on the Java DB server. "ij" uses the JDBC driver to connect to the Java DB server with the "connect" command in this format: connect 'jdbc:derby://<host>:<port>/<database>'; Create a new database and connect to that database connect 'jdbc:derby://<host>:<port>/<database>;create=true'; Connect to an existing database Here is how I used "ij" to create a new database and a new table: C:\>\local\javadb\bin\ij ij version 10.2 ij> connect 'jdbc:derby://localhost/TestDB;create=true'; ij> CREATE TABLE TestTable (ID INT, Name VARCHAR(20)); 0 rows inserted/updated/deleted

ij> INSERT INTO TestTable VALUES (1, 'Herong'); 1 row inserted/updated/deleted ij> SELECT * FROM TestTable; ID NAME -------------------------------1 Herong 1 row selected ij> quit;

Installing Microsoft JDBC Driver for SQL Server This section describes how to download and install Microsoft JDBC Driver 1.0 for SQL Server 2005. If you want to access SQL Server database from Java applications, you need to in stall a JDBC driver that supports SQL Server. There are many software vendors of fer such JDBC drivers. Microsoft offers a free driver, JDBC Driver 1.0, which is JDBC 3.0 compliant. JD BC Driver 1.0 is a Type 4 JDBC driver using native-protocols. The tutorial below shows you how to download and install the JDBC Driver 1.0 fro m Microsoft. 1. Go to Microsoft JDBC page. 2. Click the Download button. The license terms page shows up. 3. Click the link "I Accept and I want to download the Microsoft Windows version " near the end of the page. The download window shows up. 4. Save the downloaded file, sqljdbc_1.0.809.102_enu.exe, to C:\temp directory. 5. Double click on sqljdbc_1.0.809.102_enu.exe. It will be unzipped to a local d irectory called: "Microsoft SQL Server 2005 JDBC Driver". The JDBC driver .jar f ile, sqljdbc.jar, is located under the "sqljdbc_1.0\enu" subdirectory. 6. Copy sqljdbc.jar to C:\local\lib\sqljdbc.jar. You are ready to use JDBC Drive r 1.0 now.

Installing Microsoft JDBC Driver for SQL Server This section describes how to download and install Microsoft JDBC Driver 1.0 for SQL Server 2005. If you want to access SQL Server database from Java applications, you need to in stall a JDBC driver that supports SQL Server. There are many software vendors of fer such JDBC drivers. Microsoft offers a free driver, JDBC Driver 1.0, which is JDBC 3.0 compliant. JD BC Driver 1.0 is a Type 4 JDBC driver using native-protocols. The tutorial below shows you how to download and install the JDBC Driver 1.0 fro

m Microsoft. 1. Go to Microsoft JDBC page. 2. Click the Download button. The license terms page shows up. 3. Click the link "I Accept and I want to download the Microsoft Windows version " near the end of the page. The download window shows up. 4. Save the downloaded file, sqljdbc_1.0.809.102_enu.exe, to C:\temp directory. 5. Double click on sqljdbc_1.0.809.102_enu.exe. It will be unzipped to a local d irectory called: "Microsoft SQL Server 2005 JDBC Driver". The JDBC driver .jar f ile, sqljdbc.jar, is located under the "sqljdbc_1.0\enu" subdirectory. 6. Copy sqljdbc.jar to C:\local\lib\sqljdbc.jar. You are ready to use JDBC Drive r 1.0 now.

Loading Driver Class with Class.forName() This section describes how to load Microsoft JDBC Driver 1.0 class with Class.fo rName() method. The first step of using JDBC to connect to SQL Server is to load the JDBC driver class. To do this you need to use the Class.forName() method to load the driver class, com.microsoft.sqlserver.jdbc.SQLServerDriver, which represents the Micro soft JDBC Driver. Here is my sample program to load Microsoft JDBC Driver 1.0 class: /** * ConnectionTest1.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class ConnectionTest1 { public static void main(String [] args) { Connection con = null; try { // Load Microsoft JDBC Driver 1.0 Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver"); System.out.println("JDBC driver loaded ok."); } catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException: " +e.getMessage()); } } } Compile and run this program: C:\>\progra~1\java\jdk1.6.0_02\bin\javac ConnectionTest1.java C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp . ConnectionTest1

ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver I was getting this exception, because I forgot to add the JDBC driver jar file t o the classpath in the "-cp" option. Here is the correct way to run this Java pr ogram with the JDBC driver jar file: C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar ConnectionTest1 JDBC driver loaded ok. DriverManager.getConnection() and Connection URL This section describes how to use DriverManager.getConnection() and connection U RL for the Microsoft JDBC driver. Once the JDBC driver class is loaded, you are ready to connect to a SQL Server b y using the DriverManager.getConnection(connection_url) method. The connection U RL, connection_url, is a string with the following syntax: jdbc:sqlserver://server_name;user=login;password=**** The tutorial program below shows you a good example of using getConnection() and connection URL: /** * ConnectionTest2.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class ConnectionTest2 { public static void main(String [] args) { Connection con = null; try { // Load Microsoft JDBC Driver 1.0 Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Obtaining a connection to SQL Server con = DriverManager.getConnection( "jdbc:sqlserver://localhost;" + "user=sa;password=HerongYang"); } catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException: " +e.getMessage()); } catch (SQLException e) { System.err.println("SQLException: " +e.getMessage()); } } } If you run this program, you may get a surprising error like this: C:\>\progra~1\java\jdk1.6.0_02\bin\javac ConnectionTest2.java

C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar ConnectionTest2 SQLException: The TCP/IP connection to the host has failed. java.net.ConnectException: Connection refused: connect The error is probably caused by the port number where the SQL Server is listenin g for the client connection. If port number is different than the default number , you must specify the port number in the connection url as shown in the next tu torial. Specifying Port Number in Connection URL This section describes how to specify port numbers in the connection URL. If the SQL Server is configured with a non-default port number, you need to spec ify the port number in the connection url in the following syntax: jdbc:sqlserver://server_name:port;user=login;password=**** For example, if you installed the SQL Server 2005 Express Edition, it will be co nfigured with 1269 as the port number. The tutorial program below shows you how to include port number 1296 in the conn ection url: /** * ConnectionTest3.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class ConnectionTest3 { public static void main(String [] args) { Connection con = null; try { // Load Microsoft JDBC Driver 1.0 Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Obtaining a connection to SQL Server con = DriverManager.getConnection( "jdbc:sqlserver://localhost:1269;" + "user=sa;password=HerongYang"); // Connection is ready to use DatabaseMetaData meta = con.getMetaData(); System.out.println("Driver name: " + meta.getDriverName()); System.out.println("Driver version: " + meta.getDriverVersion()); System.out.println("Server name: " + meta.getDatabaseProductName()); System.out.println("Server version: " + meta.getDatabaseProductVersion()); System.out.println("Connection URL: " + meta.getURL()); System.out.println("Login name: " + meta.getUserName());

} catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException: " +e.getMessage()); } catch (SQLException e) { System.err.println("SQLException: " +e.getMessage()); } } } Compile and run it, you should get: C:\>\progra~1\java\jdk1.6.0_02\bin\javac ConnectionTest3.java C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar ConnectionTest3 Driver name: Microsoft SQL Server 2005 JDBC Driver Driver version: 1.0.809.102 Server name: Microsoft SQL Server Server version: 9.00.1399 Connection URL: jdbc:sqljdbc:// Login name: sa Closing the Database Connection - con.close() This section describes how to close database connections. When you obtained a connection object with DriverManager.getConnection() success fully, you can create statement objects and execute them with this connection ob ject. But when you are done with this connection, you should close it to free re sources associated this connection on the SQL server. To close a connection, you should call the close() method on this connection object. The tutorial program below shows you how to call close() on a connection object. isClosed() method is called to verify the status of the connection object. /** * CloseConnection.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class CloseConnection { public static void main(String [] args) { Connection con = null; try { // Load Microsoft JDBC Driver 1.0 Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Obtaining a connection to SQL Server con = DriverManager.getConnection( "jdbc:sqlserver://localhost:1269;" + "user=sa;password=HerongYang"); // Connection is ready to use DatabaseMetaData meta = con.getMetaData();

System.out.println("Server name: " + meta.getDatabaseProductName()); System.out.println("Server version: " + meta.getDatabaseProductVersion()); // Closing the connection con.close(); if (con.isClosed()) System.out.println("Connection closed."); } catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException: " +e.getMessage()); } catch (SQLException e) { System.err.println("SQLException: " +e.getMessage()); } } } If you run this program, you will get: C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar CloseConnection Server name: Microsoft SQL Server Server version: 9.00.1399 Connection closed.

Specifying Database Name in Connection URL This section describes how to specify database name in connection URL. When you create a connection object to a SQL Server without specifying any datab ase name, the SQL Server will connect you to the default database that is linked to the login name. For example, "master" is the default database for login name "sa". If you create a connection with "sa" login name, the connection will be l inked to "master" database. If you want to work with a different database, you must specify the database nam e in the connection url in the following syntax: jdbc:sqlserver://server_name:port;database=name;... The tutorial program below shows you how to connect to the local SQL Server and select the sample database "AdventureWorksLT" as the working database. /** * SelectDatabase.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class SelectDatabase { public static void main(String [] args) { Connection con = null; try {

// Load Microsoft JDBC Driver 1.0 Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Obtaining a connection to SQL Server con = DriverManager.getConnection( "jdbc:sqlserver://localhost:1269;" + "user=sa;password=HerongYang;" + "database=AdventureWorksLT"); // Checking the database name Statement sta = con.createStatement(); ResultSet res = sta.executeQuery("SELECT DB_NAME()"); res.next(); String name = res.getString(1); System.out.println("Connected to database: "+name); con.close(); } catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException: " +e.getMessage()); } catch (SQLException e) { System.err.println("SQLException: " +e.getMessage()); } } } The program output will confirm you that the database is selected correctly. C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar SelectDatabase Connected to database: AdventureWorksLT Incorrect Database Name in Connection URL This section describes what will happen if incorrect database names specified in the connection URL. If you selected a wrong database, or the login name has no access to that databa se, getConnection() method will throw a SQLExection object for you to catch. In this case, the getMessage() method of the SQLExection object will give you the d etailed error message. The tutorial program below shows you an example of the SQLException resulting fr om a wrong database name in the connection URL: /** * WrongDatabase.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class WrongDatabase { public static void main(String [] args) { Connection con = null; try { // Load Microsoft JDBC Driver 1.0

Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Obtaining a connection to SQL Server con = DriverManager.getConnection( "jdbc:sqlserver://localhost:1269;" + "user=sa;password=HerongYang;" + "database=AdventureWorksLI"); con.close(); } catch (java.lang.ClassNotFoundException e) { System.err.println("ClassNotFoundException: " +e.getMessage()); } catch (SQLException e) { System.err.println("SQLException: " +e.getMessage()); } } } You will get the following message, if you run it: C:\>\progra~1\java\jdk1.6.0_02\bin\java -cp .;\local\lib\sqljdbc.jar WrongDatabase SQLException: Cannot open database "AdventureWorksLI" requested by the login. The login failed. The error message is not so accurate. The login was correct. The select database operation was failed, because database "AdventureWorksLI" does not exist on the SQL Server.

Creating Connections with DataSource Class This section describes how to create connection objects with the DataSource clas s. It is recommended now that connection objects are created by the DataSource impl ementation class, com.microsoft.sqlserver.jdbc.SQLServerDataSource. Here is a sa mple program that creates a connection object using the DataSource class without using JNDI services: /** * SqlServerDataSource.java * Copyright (c) 2007 by Dr. Herong Yang. All rights reserved. */ import java.sql.*; public class SqlServerDataSource { public static void main(String [] args) { Connection con = null; try { // Setting up the DataSource object com.microsoft.sqlserver.jdbc.SQLServerDataSource ds = new com.microsoft.sqlserver.jdbc.SQLServerDataSource(); ds.setServerName("localhost"); ds.setPortNumber(1269);

ds.setDatabaseName("AdventureWorksLT"); ds.setUser("sa"); ds.setPassword("HerongYang"); // Getting a connection object con = ds.getConnection(); // Getting database info DatabaseMetaData meta = con.getMetaData(); System.out.println("Server name: " + meta.getDatabaseProductName()); System.out.println("Server version: " + meta.getDatabaseProductVersion()); // Closing the connection con.close(); } catch (Exception e) { System.err.println("Exception: "+e.getMessage()); } } } The output confirms that I got a good connection. Remember to include sqljdbc.ja r in the classpath for compilation and execution: C:\>javac -cp .;\local\lib\sqljdbc.jar SqlServerDataSource.java C:\>java -cp .;\local\lib\sqljdbc.jar SqlServerDataSource Server name: Microsoft SQL Server Server version: 9.00.1399

Vous aimerez peut-être aussi