How to make connection between JDBC and latest version of MySql 8.0.11 and insert a record in table with the help of Java Program

Step-1 First you create a database of university

create database university;

Step-2 After creating database now create a table of employee

create table employee(
code integer(10) primary key auto_increment,
name varchar(20),
salary double(7,2));

Step-3 Now connect mysql-connector-java-8.0.11.jar

Step-4 Now write java code which are given below

package com.app;
import java.sql.*;
import java.util.*;
public class FirstActivity
{
	public static void main(String args[])
	{
		Scanner scan=new Scanner(System.in);
		System.out.println ("Enter the name :");
		String name=scan.nextLine();
		System.out.println("enter the salary:");
		double salary=scan.nextDouble();
		try
		{
		 Class.forName("com.mysql.cj.jdbc.Driver");
		 Connection cn=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/university?autoReconnect=true&useSSl=false","root","root");
		 if(!cn.isClosed())
		 {
		 	System.out.println ("Database Server Connected");
		 	PreparedStatement ps=cn.prepareStatement("insert into employee(name,salary)values(?,?)");
		 	ps.setString(1,name);
		 	ps.setDouble(2,salary);
		 	int a=ps.executeUpdate();
		 	if(a>0)
		 	{
		 		System.out.println ("record inserted");
		 	}
		 }
		 cn.close();	
		}
		catch(Exception e)
		{
			System.out.println ("error is "+e.getMessage());
		}
	}
}

You may also like...

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x