0% found this document useful (0 votes)
7 views7 pages

Java MySQL Medicine Database Program

Uploaded by

kirti21062021
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views7 pages

Java MySQL Medicine Database Program

Uploaded by

kirti21062021
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Name -Aman kumar

Sap id -1000017717

Write a program in Java to create database

Connectivity with a database and

Display the records of the table.

a. Create a table in MySQL

b. Retrieve the all the content of the table and

Display it

c. Connect the database to your java program and

Retrieve all the table

Contents.

1 Enter up to 5 medicines details.

Medicine_name manufactured_date

Expiry_date Medicine_uses

Mysql command

CREATE DATABASE medicine_database;


USE medicine_database;

CREATE TABLE medicine (

Id INT(11) NOT NULL AUTO_INCREMENT,

Medicine_name VARCHAR(255) NOT NULL,

Manufactured_date DATE NOT NULL,

Expiry_date DATE NOT NULL,

Medicine_uses VARCHAR(255),

PRIMARY KEY (id)

);

INSERT INTO medicines (medicine_name,

Manufactured_date, expiry_date, medicine_uses)

VALUES

(‘Paracetamol’, ‘2022-01-01’, ‘2024-01-01’, ‘Pain

Relief’),

(‘Ibuprofen’, ‘2022-02-01’, ‘2024-02-01’, ‘Pain relief,


Fever reduction’),

(‘Amoxicillin’, ‘2022-03-01’, ‘2024-03-01’,

‘Antibiotic’),

(‘Loratadine’, ‘2022-04-01’, ‘2024-04-01’, ‘Allergy

Relief’),

(‘Omeprazole’, ‘2022-05-01’, ‘2024-05-01’, ‘Acid

Reflux treatment’);

Java source code

Import [Link].*;

Public class MedicineDatabase {

Public static void main(String[] args) {

String url =

“jdbc:mysql://localhost:3306/medicine_db”;

String user = “root”;

String password = “password”;

Try {
// Establish database connection

Connection conn =

[Link](url, user, password);

// Create a statement object to execute SQL

Queries

Statement stmt = [Link]();

// Create the medicine table if it does not exist

String createTable = “CREATE TABLE IF NOT EXISTS

Medicine (medicine_name VARCHAR(50), “ +

“manufactured_date DATE,

Expiry_date DATE, medicine_uses VARCHAR(200))”;

[Link](createTable);

// Insert some medicine records into the table

String insertRecord1 = “INSERT INTO medicine

VALUES (‘Aspirin’, ‘2022-01-01’, ‘2023-01-01’, ‘Pain


Relief’)”;

String insertRecord2 = “INSERT INTO medicine

VALUES (‘Tylenol’, ‘2022-02-01’, ‘2023-02-01’, ‘Fever

Reducer’)”;

String insertRecord3 = “INSERT INTO medicine

VALUES (‘Benadryl’, ‘2022-03-01’, ‘2023-03-01’,

‘Antihistamine’)”;

[Link](insertRecord1);

[Link](insertRecord2);

[Link](insertRecord3);

// Retrieve all records from the medicine table

And display them

String query = “SELECT * FROM medicine”;

ResultSet rs = [Link](query);

While ([Link]()) {
String name = [Link](“medicine_name”);

String manufDate =

[Link](“manufactured_date”);

String expDate = [Link](“expiry_date”);

String uses = [Link](“medicine_uses”);

[Link](name + “, “ + manufDate + “,

“ + expDate + “, “ + uses);

// Close the result set, statement, and connection

Objects

[Link]();

[Link]();

[Link]();

}
Catch (SQLException e) {

[Link]();

OUTPUT-

Aspirin, 2022-01-01, 2023-01-01, Pain relief

Tylenol, 2022-02-01, 2023-02-01, Fever reducer

Benadryl, 2022-03-01, 2023-03-01, Antihistamine

Common questions

Powered by AI

Transaction management could improve the program by ensuring that all database operations, such as table creation and record insertion, are completed successfully before committing changes. By using `conn.setAutoCommit(false)` and implementing `conn.commit()` after successful operations, it would prevent partial database state updates and allow for rollback capabilities in case of failures, improving data integrity and consistency .

The Java program is designed with predefined SQL INSERT statements that specify exact medicine records to be entered into the database, seen in `insertRecord1`, `insertRecord2`, and `insertRecord3`. This design simplifies testing and ensures that a consistent dataset is available for retrieval. The on-screen results from executing this program are lines displaying each medicine's data - "Aspirin, 2022-01-01, 2023-01-01, Pain relief", "Tylenol, 2022-02-01, 2023-02-01, Fever reducer", and "Benadryl, 2022-03-01, 2023-03-01, Antihistamine" .

The Java program can utilize `Scanner` or a similar input stream to take user inputs during runtime. Before executing each `INSERT INTO` statement, it can prompt the user to enter medicine details through the console, with `scanner.next()` capturing inputs for fields like `medicine_name`, `manufactured_date`, `expiry_date`, and `medicine_uses`. This input can then be concatenated into a dynamic SQL insert command which `executeUpdate` would process, thereby replacing hard-coded values with user-driven data entry .

The SQL command used to insert new medicine records is `INSERT INTO medicine VALUES (...)`. In the Java application, strings representing each record are defined, such as `insertRecord1`, `insertRecord2`, `insertRecord3`, and these are executed by calling `stmt.executeUpdate` for each insert statement .

The Java program connects to the MySQL database using the `DriverManager.getConnection` method with the URL `jdbc:mysql://localhost:3306/medicine_db`, the user name `root`, and the password `password`. It then creates a `Statement` object to execute SQL queries. The program checks if the medicine table exists and creates it with the SQL command `CREATE TABLE IF NOT EXISTS Medicine` using the `stmt.executeUpdate` method if it does not exist .

The Java program retrieves records by executing the SQL query `SELECT * FROM medicine` using `stmt.executeQuery`, which returns a `ResultSet`. It iterates over the `ResultSet` using `rs.next()`, extracting each field's data with `rs.getString(field_name)` methods. It then displays the data by concatenating and printing these values in a formatted string .

In the MySQL table, dates are handled as `DATE` data types, reflecting a straightforward date storage format. In the Java program, date fields are retrieved from the database as strings using `rs.getString("field_name")`, which converts the SQL DATE format into a string representation that can be easily printed and manipulated. This typifies the conversion between database storage formats and Java's data handling, ensuring compatibility and ease of use .

The `CREATE TABLE IF NOT EXISTS` SQL command allows the program to conditionally create a table only if it doesn't already exist, preventing potential errors or exceptions from trying to create a duplicate table. This is a proactive measure that ensures the program can run multiple times without reinitialization errors, enhancing its robustness and flexibility in a production environment .

Java exceptions, specifically `SQLException`, are used to manage database connectivity issues. The `try` block wraps the connection, table creation, and data retrieval logic, while the `catch(SQLException e)` block handles any SQL-related errors, printing the stack trace for debugging. This prevents the program from crashing and provides useful information for resolving connectivity issues .

The current Java program is vulnerable to several security risks such as SQL injection, hardcoded credentials, and lack of encryption. Directly concatenated SQL commands can be exploited with injection attacks because user input is not sanitized. The hardcoded username and password offer an easy attack vector if accessed by unauthorized users. Additionally, the connection string lacks SSL encryption, exposing data to potential interception during transmission. Implementing parameterized queries, environment variable-based credential management, and enabling SSL can mitigate these vulnerabilities .

You might also like