Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ganesh_JavaSE7_Programming_1z0-804_study_guide.pdf
Скачиваний:
94
Добавлен:
02.02.2015
Размер:
5.88 Mб
Скачать

Chapter 10 Building Database Applications with JDBC

Connecting to the Database

The first step to communicate with your database is to set up a connection between your application and the database server. Listing 10-1 shows a simple application to acquire a connection.

Listing 10-1.  DbConnect.java

import java.sql.*;

// The class attempts to acquire a connection with the database class DbConnect {

public static void main(String[] args) {

//url points to jdbc protocol : mysql subprotocol; localhost is the address

//of the server where we installed our DBMS (i.e. on local machine) and

//3306 is the port on which we need to contact our DBMS

String url = "jdbc:mysql://localhost:3306/";

//we are connecting to the addressBook database we created earlier String database = "addressBook";

//we login as "root" user with password "mysql123"

String userName = "root"; String password = "mysql123";

try (Connection connection = DriverManager.getConnection (url + database, userName, password)){

System.out.println("Database connection: Successful"); } catch (Exception e) {

System.out.println("Database connection: Failed"); e.printStackTrace();

}

}

}

Let’s analyze the program step by step:

1.The URL of jdbc:mysql://localhost:3306/ indicates that jdbc is the protocol and mysql is a subprotocol; localhost is the address of the server where we installed our DBMS

(i.e., on local machine), and 3306 is the port on which we need to contact our DBMS. (Note that this port number will be different when you use some other database. In fact, we used the default port number provided by the MySQL database, which can be changed if required. Additionally, if you are using some other database, the subprotocol will also change.) You need to use the addressBook database with root credentials.

2.You can get a connection object by invoking the DriverManager.getConnection() method; the method expects the URL of the database along with a database name, user name, and password.

3.You need to close it before coming out of the program. This example uses a try-with-resources statement; hence the close() method for connection will be automatically called.

4.If anything goes wrong, you will get an exception. In that case, it will print the stack trace of the exception.

286

Chapter 10 Building Database Applications with JDBC

Okay, now run this program. Here is the output:

Database connection: Failed

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/addressBook at java.sql.DriverManager.getConnection(DriverManager.java:604)

at java.sql.DriverManager.getConnection(DriverManager.java:221) at DbConnect.main(DbConnect.java:16)

Oops! What happened? Why did you get this SQLException? Well, it is a common mistake to forget to add the path of the jar in the classpath environment variable. In this case, the JDBC API will not be able to locate the JDBC driver and so will throw this exception. Remember, entering only the path of the jar is not enough; you need to add the jar name along with the full path also of the classpath variable.

 You need to put the full path of the jar file of your JDBC driver to avoid getting an exception for

“no suitable driver found.” In fact, entering only the path of the jar is not enough; you need to add the jar name along with the full path to the classpath variable.

Okay, let’s update the classpath variable and then try again. If you attempt the same program; you might get another exception:

Database connection: Failed

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)

[. . . rest of the stack trace elided . . .]

In this program, we’ve given the username “root” and password “mysql123”. If you’ve set the root user password to something else, you’ll get this exception with the message “access denied for user.” There are two ways to fix this problem. The first way is to change the program to give your password instead of the “mysql123” we’ve used in this program. The second way is to reset the password in your database. For MySQL, you can reset your password as follows for the user “root”:

UPDATE mysql.user SET Password=PASSWORD('mysql123') WHERE User='root';

FLUSH PRIVILEGES;

Here is the output if this program runs successfully:

Database connection: Successful

When you see this output, it means that you are able to establish a connection with the database. If you want to try out the programs in the rest of this chapter, you should get this program working in your system; you need to establish a connection to query or update the database.

 You’ve already seen two examples of SQLException thrown from the JDBC API. When you get a SQLException, you can rarely do anything in the program to recover from it. What you can do in a realworld application is to wrap it as a higher-level exception and rethrow it to the calling component. To save space in code segments, we’ll just print the stack trace of the exception and ignore it in the programs in this chapter.

287

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]