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

Chapter 10 Building Database Applications with JDBC

The program prints the following:

Table created successfully

The program is working as expected. Here, you connect to the database and get the statement object as you did earlier. Then, you issue a SQL statement using the Update() method. Using the SQL statement, you declare that a table called familyGroup needs to be created along with two columns: id and nickName. Also, you declare that id should be treated as the primary key. That’s it; the SQL statement creates a new table in your database.

Note that the syntax of the SQL statement is your responsibility. If you pass a wrong SQL statement, you will get a

MySQLSyntaxErrorException belonging to the com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException.

Getting the Database Metadata

You can get the metadata from a Connection object to examine the capabilities of the underlying database. You can do this by calling the getMetaData() method in the Connection interface; its return type is DatabaseMetaData. This DatabaseMetaData is a rich class that provides a large number of methods to examine the database details. For example, you can check the kind of transactions the database supports, the maximum number of columns you can have in a table, etc. Listing 10-10 will make it clearer to you.

Listing 10-10.  DbConnectionMetaData.java

import java.sql.*;

//To illustrate how to obtain metadata from Collection object

//and examine the metadata for using it in a program

class DbConnectionMetaData {

public static void main(String []args) throws SQLException { Connection connection = DbConnector.connectToDb(); DatabaseMetaData metaData = connection.getMetaData();

System.out.println("Displaying some of the database metadata from the Connection object");

System.out.println("Database is: " + metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion());

System.out.println("Driver is: " + metaData.getDriverName() + metaData. getDriverVersion());

System.out.println("The URL for this connection is: " + metaData.getURL()); System.out.println("User name is: " + metaData.getUserName()); System.out.println("Maximum no. of rows you can insert is: " + metaData. getMaxRowSize());

}

}

It prints the following:

Displaying some of the database metadata from the Connection object Database is: MySQL 5.5.27

Driver is: MySQL-AB JDBC Drivermysql-connector-java-5.1.21 ( Revision: ${bzr.rev ision-id} )

The URL for this connection is: jdbc:mysql://localhost:3306/addressBook User name is: root@localhost

Maximum no. of rows you can insert is: 2147483639

299

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