How to create database in mysql with connection object conn (Student Class Example)

Java code for inserting data into database is done using Jdbc(Java Database connectivity).

Jdbc is a API to connect java program to various databases like MySql, Oracle, MSAccess etc.

Here Step by step tutorial to insert data from java to database.

Here MySql or MariaDB database is used for this purpose.

So to insert data in database we need to set in two end

  1. Create Database and table
  2. Write Java (JDBC) code

Lets see them one by one

Create Database and table

Open phpMyAdmin click on home icon or left side

Click to SQL on middle menu.

Write create query given below

Copy and insert above code in SQL query box

create table query

After click on go button it will show below box if query is successfully executed.

created table query

You can see structure of table. which show below output.

table structure

Now table is created.

Write JDBC Code

Steps for JDBC is as below

  1. import JDBC classes
  2. Load and register JDBC Driver
  3. Open Database connection
  4. Create Statement object to pass query
  5. Execute Statement
  6. Get the result
  7. Close connections

File Structure of Program

file explorer

Importing JDBC classes

Load and register JDBC Driver

Here Class.forName() is used to load and register driver

Open Database connection

Create Statement object to pass query

Execute Statement and get result

Here ps.executeUpdate() execute query and get no of row affected.

Close connections

pre class=”theme:eclipse font:verdana toolbar:2 show-plain:3 lang:java decode:true”> con.close();

Insert a Student Object into database

Before proceeding add mysql-connector-java-5.1.14-bin.jar to your class path.

All file details are as below.

Student.java

Student object that contains basic properties of students like id, rollNo, name, branch,section, emailId,dob, mobileNo, addDate.

ConnectionFactory .java

This file is responsible to connect with MySql database, after getting connection this will return connection object

StudentJDBCInsert.java

This class will get connection from ConnectionFactory and insert data in database and return no of rows inserted in database.

Output

Insert multiple Student Objects into database

efficient way to insert multiple records in database is using batch processing

Steps to store multiple records in database

  1. Create multiple objects
  2. Add all to a List
  3. Add list item to batch
  4. executeBatch()

StudnetJDBCBatchInsert.java

this program will insert batch data to MySql database

Output

MySql Admin view

data in MySql table

Reading Data using JDBC

StudentJDBCRead .java

This program read student records from database table and show in java console.

Output

Download above code fron github