Loading jdbc driver in java

Establishing JDBC Connection in Java

Before establishing a connection between the front end i.e your Java Program and the back end i.e the database we should learn what precisely a JDBC is and why it came into existence. Now let us discuss what exactly JDBC stands for and will ease out with the help of real-life illustration to get it working.

What is JDBC?

JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open Database Connectivity ). JDBC is a standard API specification developed in order to move data from frontend to the backend. This API consists of classes and interfaces written in Java. It basically acts as an interface (not the one we use in Java) or channel between your Java program and databases i.e it establishes a link between the two so that a programmer could send data from Java code and store it in the database for future use.

Illustration: Working of JDBC co-relating with real-time

Why JDBC Come into Existence?

As previously told JDBC is an advancement for ODBC, ODBC being platform-dependent had a lot of drawbacks. ODBC API was written in C, C++, Python, and Core Java and as we know above languages (except Java and some part of Python )are platform-dependent. Therefore to remove dependence, JDBC was developed by a database vendor which consisted of classes and interfaces written in Java.

Steps For Connectivity Between Java Program and Database

  1. Import the Packages
  2. Load the drivers using the forName() method
  3. Register the drivers using DriverManager
  4. Establish a connection using the Connection class object
  5. Create a statement
  6. Execute the query
  7. Close the connections

Let us discuss these steps in brief before implementing by writing suitable code to illustrate connectivity steps for JDBC/

Step 1: Import the Packages

Step 2: Loading the drivers

Читайте также:  Select all radio buttons javascript

In order to begin with, you first need to load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of two ways mentioned below as follows:

2-A Class.forName()

Here we load the driver’s class file into memory at the runtime. No need of using new or create objects. The following example uses Class.forName() to load the Oracle driver as shown below as follows:

Class.forName(“oracle.jdbc.driver.OracleDriver”);

2-B DriverManager.registerDriver()

DriverManager is a Java inbuilt class with a static member register. Here we call the constructor of the driver class at compile time. The following example uses DriverManager.registerDriver()to register the Oracle driver as shown below:

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())

Step 3: Establish a connection using the Connection class object

After loading the driver, establish connections as shown below as follows:

Connection con = DriverManager.getConnection(url,user,password)
  • user: Username from which your SQL command prompt can be accessed.
  • password: password from which the SQL command prompt can be accessed.
  • con: It is a reference to the Connection interface.
  • Url: Uniform Resource Locator which is created as shown below:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”

Where oracle is the database used, thin is the driver used, @localhost is the IP Address where a database is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String type and are to be declared by the programmer before calling the function. Use of this can be referred to form the final code.

Step 4: Create a statement

Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:

Statement st = con.createStatement();

Note: Here, con is a reference to Connection interface used in previous step .

Step 5: Execute the query

Now comes the most important part i.e executing the query. The query here is an SQL Query. Now we know we can have multiple types of queries. Some of them are as follows:

The executeQuery() method of the Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table.
The executeUpdate(sql query) method of the Statement interface is used to execute queries of updating/inserting.

Читайте также:  For через итераторы java

Pseudo Code:

int m = st.executeUpdate(sql); if (m==1) System.out.println("inserted successfully : "+sql); else System.out.println("insertion failed");

Here sql is SQL query of the type String

Источник

Работа с базами данных с помощью JDBC драйвера

В этом уроке я бы хотел вас научить работать с базами данных MySQL, PostgreSQL, Oracle. А именно как подключится и выполнять SQL запросы к базе с помощью java.

Что такое JDBC?

JDBC Driver – (Java DataBase Connectivity — соединение с базами данных на Java) — платформенно-независимый промышленный стандарт взаимодействия Java-приложений с различными СУБД, реализованный в виде пакета java.sql , входящего в состав Java SE.

Зачем нужен JDBC?

JDBC – позволяет получать доступ к БД, а также выполнять к ней SQL запросы.

jdbc_scheme

Шаг 1.

Скачиваем jar файл JDBC драйвера.

Шаг 2.

Подключение к БД Mysql:

Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password"); conn.close();

Подключение к БД PostgreSQL:

Class.forName("org.postgresql.Driver"); Connection connection = DriverManager.getConnection("jdbc:postgresql://hostname:port/dbname","username", "password"); connection.close();

Подключение к БД Oracle:

Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:mkyong","username","password"); connection.close();

В 1-й строке мы указываем наш JDBC драйвер. Не забудьте добавить его в ClassPath иначе его компилятор его не увидит.
Во 2-й строке JDBC Manager который открывает соединение с базой данных и обеспечит нам дальнейшее обращение к ней.
И последняя строка закрывает соединение с БД.

Желательно строку для определения JDBC поместить в блок try для того чтобы контролировать его наличия в вашем приложении.

try < Class.forName("com.mysql.jdbc.Driver"); >catch (ClassNotFoundException e)

Шаг 3. Создание таблиц в БД.

Вынесем в отдельный метод соединение с БД.

private static Connection getDBConnection() < Connection dbConnection = null; try < Class.forName(DB_DRIVER); >catch (ClassNotFoundException e) < System.out.println(e.getMessage()); >try < dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,DB_PASSWORD); return dbConnection; >catch (SQLException e) < System.out.println(e.getMessage()); >return dbConnection; >

Этот метод будет создавать в БД таблицу:

private static void createDbUserTable() throws SQLException < Connection dbConnection = null; Statement statement = null; String createTableSQL = "CREATE TABLE DBUSER(" + "USER_ID NUMBER(5) NOT NULL, " + "USERNAME VARCHAR(20) NOT NULL, " + "CREATED_BY VARCHAR(20) NOT NULL, " + "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) " + ")"; try < dbConnection = getDBConnection(); statement = dbConnection.createStatement(); // выполнить SQL запрос statement.execute(createTableSQL); System.out.println("Table \"dbuser\" is created!"); >catch (SQLException e) < System.out.println(e.getMessage()); >finally < if (statement != null) < statement.close(); >if (dbConnection != null) < dbConnection.close(); >> >

и в main методе вызываем метод createDbTable() который создаст таблицу в БД.

public static void main(String[] argv) < try < createDbUserTable(); >catch (SQLException e) < System.out.println(e.getMessage()); >>

В результате вы должны получить:

CREATE TABLE DBUSER( USER_ID NUMBER(5) NOT NULL, USERNAME VARCHAR(20) NOT NULL, CREATED_BY VARCHAR(20) NOT NULL, CREATED_DATE DATE NOT NULL, PRIMARY KEY (USER_ID) ) TABLE "user" IS created!

Шаг 4. Добавление новой записи в БД.

String insertTableSQL = "INSERT INTO DBUSER" + "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) " + "VALUES" + "(1,'mkyong','system', " + "to_date('" + getCurrentTimeStamp() + "', 'yyyy/mm/dd hh24:mi:ss'))";

метод который будет возвращать текущую дату и время:

Читайте также:  Python печать в pdf

private static String getCurrentTimeStamp()

И выполняем наш SQL запрос который лежит в переменной insertTableSQL

statement.executeUpdate(insertTableSQL);

Шаг 5. Получение данных с БД.

String selectTableSQL = "SELECT USER_ID, USERNAME from DBUSER";

try < dbConnection = getDBConnection(); statement = dbConnection.createStatement(); // выбираем данные с БД ResultSet rs = statement.executeQuery(selectTableSQL); // И если что то было получено то цикл while сработает while (rs.next()) < String userid = rs.getString("USER_ID"); String username = rs.getString("USERNAME"); System.out.println("userid : " + userid); System.out.println("username : " + username); >> catch (SQLException e)

Шаг 6. Удаление данных с БД.

String deleteTableSQL = "DELETE DBUSER WHERE USER_ID = 1";

Выполняем запрос на удаление:

Шаг 7. Обновление данных в БД.

String updateTableSQL = "UPDATE DBUSER SET USERNAME = 'mkyong_new' WHERE USER_ID = 1";

Выполняем запрос на обновление записи:

Выводы.

Все действия с любой базой данных выполняются через SQL запросы, то есть нам достаточно знать SQL для манипуляцией данными в БД.

ПОХОЖИЕ ПУБЛИКАЦИИ

29 комментариев к статье «Работа с базами данных с помощью JDBC драйвера»

Проблема с подключением jdbc к приложению для Android – заголовок комментария. Почему в жизни так бывает … строка Connection connection = DriverManager.getConnection(“jdbc:postgresql://хост:порт/имя_дб”,”пользователь”, “пароль”);
выдаёт ошибку Unhandled exception type SQLException
( строка connection.close(); – выдаёт туже ошибку ) При добавлении строки import java.sql.SQLException; в MainActivity.java
выводит сообщение …
The import java.sql.SQLException is never used При этом файл postgresql-9.2-1002.jdbc4.jar лежит в /libs И в classpath добавлять пробовал, хотя многие источники говорят, что это не обязательно, достаточно держать файл postgresql-9.2-1002.jdbc4.jar в /libs При нажатие ctrl+shift+O Eclips добавляет только: import java.sql.Connection;
import java.sql.DriverManager; А к чему приводит ручное добавление строки import java.sql.SQLException; описано в комментарии чуть выше. Поможете решить проблему?

Станислав, потому что для Android так не прокатит. Почитайте это Работа с базой данных SQLite или это Как работать с MySQL в Android? Часть 1.

Источник

Оцените статью