File

advertisement
JDBC
A Basic MySQL Tutorial
• MySQL is an open source database management
software that helps users store, organize, and
retrieve data. It is a very powerful program with a
lot of flexibility
• Once you have MySQL installed on your system
you can access the MySQL shell by typing the
following command into terminal:
mysql -u root -p
After entering the root MySQL password into the
prompt, you will be able to start building your
MySQL database.
How to Create and Delete a MySQL Database
• MySQL organizes its information into databases;
each one can hold tables with specific data. You
can quickly check what databases are available by
typing:
SHOW DATABASES;
• Creating a database is very easy:
CREATE DATABASE database name;
• In MySQL, the phrase most often used to delete
objects is Drop. You would delete a MySQL
database with this command:
DROP DATABASE database name;
How to Access a MySQL Database
• Once we have a new database, we can begin to
fill it with information. The first step is to create a
new table within the larger database.for this we
have to open up the database we want to use
USE employee;
• you can also see an overview of the tables that
the database contains.
SHOW tables;
Since this is a new database, MySQL has nothing
to show, and you will get a message that says,
“Empty set”
How to Create a MySQL Table
CREATE TABLE human_resource (id INT NOT
NULL PRIMARY KEY, name VARCHAR(20), age
int not null ,hire_date DATE);
CREATE TABLE finance (id INT NOT NULL
PRIMARY KEY, name VARCHAR(20), sex
char(1),hire_date DATE);
• take a look at how the table appears within
the database using the
SHOW TABLES; command:
• We can remind ourselves about the table’s
organization with this command:
DESCRIBE human_resource;
• N.B MySQL command line does not pay
attention to cases but the table and database
names are case sensitive: potluck is not the
same as POTLUCK or Potluck.
• How to Add Information to a MySQL Table
INSERT INTO human_resource values (123,
‘alemu', 23, '2009-09-14 ‘); INSERT INTO
human_resource values (125, ‘kebede', 28,
'2000-11-14 ‘);
INSERT INTO finance values (111, ‘almaz', ‘F’,
‘1984-09-12 ‘); INSERT INTO finance values
(112, ‘solomon', ‘M’, ‘2001-02-12 ‘);
• We can take a look at our table:
mysql> SELECT * FROM human_resource;
• Wampserver is a s/w bundle for mysql, php
,apache and php my admin
• Php my admin is a web based application
which helps you to manage mysql database
server
• How to create a database ,table,fields?
• How to view tables in a data base, fields in a
table?
• How to create a user? Using php myadmin
• JDBC is a collection of classes and interfaces(it
is an API) which helps your java application to
connect with any relational database systems
(like oracle, sql server,mysql, ms-acess and soon)
• JDBC is an interface between your java
application and the database system.
• It is to mean Java database connectivity
• JDBC was included in the java programming
world very early as part of JDK 1.1 in 1997
since then it continues to be part of different
releases of JDK
• The history of JDBC is the history of added
features and improved performance
• The original release (in 1997 )includes the
main classes and interfaces that you find
yourself using all the time. These are the
connection interface-which let you make your
initial connection with the database
Statement interface-which incapsulates the
SQL code
ResultSet interface-Which returns data from
the server
• Later versions of JDBC improved the features
of the API. Like updating your data without
SQL, Scrolling and more data types
• Recent releases included more data type, the
ability to get metadata i.e lists of table and
column information from your database
• In more recent release JDBC 4.0 was released
in java6 and it included the ability to load
drivers automatically.(no more
Class.forName())
Using JDBC drivers
• Applications that use JDBC API require drivers
• A JDBC driver is a software library that communicates
between a java application and a database.
• All JDBC drivers use the same set of rules that is the
API which is defined in java SE.
• A driver library package will contain specific
implementation of the interfaces defined in the API
e.g Connection,ResultSet,Statement,…
• Typically you get your driver packages from database
vendors
i.e mysql driver from mysql ,oracle driver from oracle
• There are 4 types of drivers distinguished by
their architecture
• These are Type-1(JDBC-ODBC bridge),Type-2
(Native API driver),Type-3(network-protocol
drivers),Type-4(java thin driver)
• Reading assignment
Differentiate the architectural difference
between these drivers.
What is the advantage and pitfall observed on
each driver type.
• The most popular driver type is Type-4 driver which
we use now for our JDBC application
• To connect to mysql you need a java driver and you
can get a free driver from
www.mysql.com/downloads/ and look for
connector/J
• (the J stands for Java)—a JDBC driver that allows
programs to use JDBC to interact with MySQL.
1. Open a Command Prompt and start the database server
by executing the command
mysqld.exe. This command has no output—it simply starts
the MySQL server. Do not close this window—doing so
terminates the server.
2. Next, you’ll start theMySQL monitor so you can set up a
user account, open another Command Prompt and execute
the command
mysql -h localhost -u root
• The -h option indicates the host (i.e., computer) on which
the MySQL server is running—in this case your local
computer (localhost). The -u option indicates the user
account that will be used to log in to the server—root is the
default user account that is created during installation to
allow you to configure the server.Once you’ve logged in,
you’ll see a mysql> prompt at which you can type
commands to interact with the MySQL server.
• At the mysql> prompt, type
USE mysql;
• and press Enter to select the built-in database named
mysql, which stores server information, such as user
accounts and their privileges for interacting with the
server. Each command must end with a semicolon. To
confirm the command, MySQL issues the message
“Database changed.”
• Next, you’ll add the dbuser user account to the mysql
built-in database. The mysql database contains a table
called user with columns that represent the user’s
name, password and various privileges. To create the
dbuser user account with the password dbpassword,
execute the following commands from the mysql>
prompt:
create user ‘dbuser'@'localhost' identified by ‘dbpassword';
grant select, insert, update, delete, create, drop,
references,execute on *.* to ‘dbuser'@'localhost';
• Type the command
exit; to terminate the MySQL monitor.
Manipulating Databases with JDBC
• This section introduces how to connect to a database
and query it.
• Create a user ‘dbuser’ with a password ‘dbpassword’
• And login to the mysql prompt with this user and
check that you have the database explorecalifornia
• If this database is not existing, import the SQL
source (if you are using the command line, execute
the explorecalifornia.sql script by using the source
command. If you are using an IDE import the .sql
script)-LAB session
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbTest{
static final String
USERNAME="dbuser";
static final String
PASSWORD="dbpassword";
static final String CONN_STRING=
"jdbc:mysql://localhost/exploreca
lifornia";
public static void main(String[]
args)throws SQLException
{
Connection conn=null;
try{
conn=DriverManager.getConnecti
on(CONN_STRING,USERNAME,
PASSWORD);
System.out.println("connected");
}catch(SQLException sqlException
)
{
sqlException.printStackTrace();
} // end catch
finally{
if(conn !=null){
conn.close();
}
}
}
}
• public static void main(String[] args)throws
SQLException in place of this we can use the trycatch block as
finally{
try
{
conn.close();
}catch ( Exception exception )
{
exception.printStackTrace();
} //end of catch
}//end of finally
• For MYSQL you include the file mysql-connector-java5.1.29-bin.jar (in the C:\mysql-connector-java-5.1.29
directory)in your programs class path.
• So to execute the code
C:\java3>javac DbTest.java
C:\java3>java -classpath .;C:\mysql-connector-java5.1.29\mysql-connector-java-5.1.29-bin.jar DbTest
• How to include and locate the driver(mysql-connectorjava-5.1.29-bin.jar) in IDE’s e.g Eclipse? LAB session
• In past versions of Java, programs were required to load
an appropriate database driver before connecting to a
database. JDBC 4.0 and higher support automatic driver
discovery— you’re no longer required to load the
database driver in advance.
public static void main(String[] args)throws SQLException
{
NO MORE!
//Class.forName(“com.mysql.jdbc.Driver”);
Connection conn=null;
try{
…..
• If the period (.) at the beginning of the class path
information is missing, the JVM will not look for
classes in the current directory and thus will not find
the DbTest class file.
Connecting to the Database
• a Connection object (package java.sql) referenced by
Conn( An object that implements interface Connection
)manages the connection between the Java program
and the database.
• The program initializes connection with the result of a
call to static method getConnection of class
DriverManager (package java. sql), which attempts to
connect to the database specified by its URL.
• Method get-Connection takes three arguments—a
String that specifies the database URL, a String that
specifies the username and a String that specifies the
password.
• The URL locates the database (possibly on a network or
in the local file system of the computer).
• The URL jdbc:mysql://localhost/explorecalifornia
specifies the protocol for communication (jdbc), the
subprotocol for communication (mysql) and the
location of the database (//localhost/explorecalifornia
where localhost is the host running the MySQL server
and explorecalifornia is the database name).
• The subprotocol mysql indicates that the program uses
a MySQL-specific subprotocol to connect to the MySQL
database. If the DriverManager cannot connect to the
database, method getConnection throws a
SQLException (package java.sql).
Figure below lists the JDBC driver names and
database URL formats of several popular RDBMSs.
Creating a statement for executing queries
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
public class DbTest{
private static final String USERNAME="dbuser";
private static final String
PASSWORD="dbpassword";
private static final String CONN_STRING=
"jdbc:mysql://localhost/explorecalifornia";
while(rs.next() )
{
for ( int i = 1; i <= 2; i++ ){
System.out.print(rs.getObject( i ) );
System.out.print("\t");
}
System.out.println();
} // end while
public static void main(String[] args)throws
SQLException
{
Connection conn=null;
//System.out.println("connected");
}catch(SQLException sqlException )
{
sqlException.printStackTrace();
} // end catch
finally{
{
Statement stmt=null;
ResultSet rs=null;
rs.close();
stmt.close();
try{
conn=DriverManager.getConnection(CONN_STRI
NG,USERNAME,PASSWORD);
conn.close();
}
}
}
}
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from
states");
• Creating a Statement for Executing Queries
stmt = conn.createStatement();
invokes Connection method createStatement to obtain an
object that implements interface Statement (package
java.sql). The program uses the Statement object to submit
SQL statements to the database.
• Executing a Query
the Statement object’s executeQuery method is used to submit
a query that selects all the states information from table
states. This method returns an object that implements
interface ResultSet and contains the query results. The
ResultSet methods enable the program to manipulate the
query result.
• Processing a Query’s ResultSet
ResultSetMetaData metaData = rs.getMetaData();
obtains the metadata for the ResultSet as a
ResultSetMetaData (package java.sql) object.
• The metadata describes the ResultSet’s contents.
Programs can use metadata programmatically to obtain
information about the ResultSet’s column names.
• int numberOfColumns = metaData.getColumnCount();
uses ResultSetMetaData method getColumnCount to
retrieve the number of columns in the ResultSet.
• First, the program positions the ResultSet cursor (which
points to the row being processed) to the first row in the
ResultSet with method next. Method next returns boolean
value true if it’s able to position to the next row;
otherwise, the method returns false.
• Initially, a ResultSet cursor is positioned before the first row.
A SQLException occurs if you attempt to access a ResultSet’s
contents before positioning the ResultSet cursor to the first
row with method next.
• If there are rows in the ResultSet, the for…loop extract and
display the contents of each column in the current row.
• For simplicity, this example treats each value as an Object.
We retrieve each column value with ResultSet method
getObject then print the Object’s String representation.
Unlike array indices, ResultSet column numbers start at 1.
How to get the column name and number of columns?
import java.sql.ResultSetMetaData;
rs = statement.executeQuery(
"SELECT * from states" );
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.println( “States Table of explorecalifornia database:\n" );
for ( int i = 1; i <= numberOfColumns; i++ )
{
System.out.print( metaData.getColumnName( i ) );
System.out.print(“\t”);
}
System.out.println();
while(resultSet.next() )
{
Basic steps to use
a database in Java
•
•
•
•
•
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
32
1. Establish a connection
• import java.sql.*;
• Load the vendor specific driver
– Class.forName(“com.mysql.jdbc.Driver”);
– What do you think this statement does, and how?
• Dynamically loads a driver class, for mysql database
• Make the connection
– Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/explorecalifornia ", username,
passwd);
• What do you think this statement does?
• Establishes connection to database by obtaining
a Connection object
33
2. Create JDBC statement(s)
• Statement stmt = con.createStatement() ;
• Creates a Statement object for sending SQL statements to the
database
34
Executing SQL Statements
• stmt.executeUpdate (“INSERT INTO states VALUES ( ‘AA',
‘Addis Ababa' )”);
• stmt.executeUpdate (“INSERT INTO states VALUES (
‘DZ', ‘Debrezeit' )”);
• stmt.executeUpdate("delete from states where
stateID='DZ'");
• String str = "Create table Lehigh(SSN Integer
not null, Name VARCHAR(32),Marks Integer)";
stmt.executeUpdate(str);
35
Get ResultSet
String queryStates = "select * from states";
ResultSet rs = Stmt.executeQuery(queryStates);
while (rs.next()) {
……
}
36
Close connection
• rs.close();
• stmt.close();
• con.close();
37
Download