Java DataBase (JDBC)

Source: Internet
Author: User

A Brief review of Database

Database (DB):

An organised collection of data

Relational DBs (first published by Edgar F. Codd (IBM) in 1970) store data in:

Tables a table in A database consists of:

Rows & Columns

Rows:records

Columns:attributes of the records

Sql:

Structured Query Language, the industry standard database query Language (relational database)

A Brief Review of Database (cont.)

SELECT NAME, ID from STUDENT WHERE gender= ' MALE ';

INSERT into STUDENT VALUES (6, ' MARY ', ' FEMALE ');

DELETE from STUDENT WHERE name= ' JERRY '; DROP TABLE STUDENT;

Overview of JDBC Cont.

Java DataBase Connectivity:java.sql

  Major components in JDBC:

  The JDBC API gives access of programming data from the Java. By using the JDBC APIs, applications can execute SQL statements and retrieve results and updation to the database. It Standardise:

-way to establish connection to database

-approach to initiating queries

-the data structure of query result

-it does not standardise SQL syntax

-jdbc Driver Manager is the class in JDBC API.

-the objects of this class can connect Java applications to a JDBC driver

How to use JDBC

Establishing a connection to DB

Create a Statement instance to conduct SQL statements

  Execute queries from JDBC

  Receive, hold and process query results from DB

Check meta-information of results & Databases

1) Establish a connection

Creates instance of a Connection object

  Connection conn = drivermanager.getconnection ("url", "username", "password"); [Throws SQLException]

  String url= "Jdbc:derby://Localhost:1527/cardb; Create=true ";

Return Connection object:creates a Statement object for sending SQL statements to the database.

2) Statement

Statement:object that can accept and execute a string that is a SQL Statement

  Statement Statement = Conn.createstatement ();

Executing statements:

  Statement.executexxxxx ("A SQL statement");

Exa

  Executeupdate:for database Modifications//modification of databases

  Executequery:for database queries//query

  Execute DB UPDATE statement:

  Statement.executeupdate ("CREATE TABLE cartable");

Example:

public void CreateTable () {

try{

Statement statement=conn.createstatement (); Create a new statement

String newtable= "Cartable"; TableName

Statement.executeupdate ("drop table if exists" +newtable); Update

String sqlcreatetable= "CREATE TABLE" +newtable+ "(ID int," + "Make VARCHAR (), MODEL VARCHAR (), Price INT)";

Statement.executeupdate (sqlcreatetable);//Update database

} catch (SQLException ex) {

System.err.println ("SQLException:" + ex.getmessage ());

}

}

Query Statement//data queries

Execute DB Query Statement:

Resultset:an object of type ResultSet is like a cursor (cursor)

Next () advances cursor to next tuple (array):

The first time next () returns the first tuple

If no more tuples then next () returns FALSE

Accessing components of a tuple:

GetXXX (attribute name OR column index)

  ResultSet rs=statement.executequery ("SELECT * from CAR");

while (Rs.next ()) {

  String attribute1= rs.getstring ("A1");

  int attribute2= Rs.getint (2);

}

More methods control the cursor:

Previous (): Moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row.

First ()/last (): Moves the cursor to the First/last row

Afterlast (): Moves the cursor to the end of this ResultSet object, just after the last row

Beforefirst (): Moves the cursor to the front of this ResultSet object, just before the first row

Public ResultSet Getquery () {//Database result set data table

ResultSet Rs=null;

try {

Statement statement=mysqlconn.createstatement ();

String sqlquery= "Select model, price from car" + "where brand= ' Toyota '";

Rs=statement.executequery (sqlquery);

  while (Rs.next ()) {

  String model= rs.getstring ("model");

  String model= rs.getstring (1);

  int price = Rs.getint (2);

System.out.println (model+ ": $" +price);

  }

System.out.println ("Table created");

} catch (SQLException ex) {

Logger.getlogger (DBOperations.class.getName ()). log (Level.severe, NULL, ex);

}

return (RS);

}

ResultSet metadata:

Resultsetmetadata:objects that can hold ResultSet metadata

ResultSetMetaData RSMD = rs.getmetadata ();

To get number of columns: rsmd.getcolumncount ();

To get the table name of a given column in the result set: rsmd.gettablename (int);

To get data type of a given column: rsmd.getcolumntype (int);

Closing:

Close ResultSet:

  Rs.close ();

Close Statement:

  Statement.close ();

Close Connection:

  Conn.close ();

A statement would be closed if the connection instance it belongs-is closed;

A resultset would be closed if the statement instance it holds results for is closed.

Java DataBase (JDBC)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.