Java Program To Insert Value into Database/Table.
The import statement imports the SQL classes required to connect to database and perform insert operation.
import java.sql.*;
public class Insert_Values {
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
try
{
String query="Insert into test_1 (Id,Name) values('2','Karan')";
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root@123");
Statement stmt=con.createStatement();
int res=stmt.executeUpdate(query);
System.out.println("Records Inserted");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
public class Insert_Values {
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
try
{
String query="Insert into test_1 (Id,Name) values('2','Karan')";
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root@123");
Statement stmt=con.createStatement();
int res=stmt.executeUpdate(query);
System.out.println("Records Inserted");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Records Inserted.
Check program by manually firing select query on database.
- import java.sql.*;- This statement imports sql package so that we can use it's classes and methods for interacting with Database. Java.sql package contains large number of classes and methods with the help of which we can perform various operations with Database.
- public class Insert_Values- is the name of the class.
- public static void main(String[] args) - is the main() method . i.e entry point for every JAVA Program.
- Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root@123");- We have created a object of Connection class using static method getConnection(); passing the parameters the database server name jdbc:mysql hostname as localhost, database name as test , user id root and password root@123.
- String query- Variable which stores the SQL query to Execute.
- Next to execute sql query we have to create a Statement object using Statement Class. There is a createStatement() method in Connection class.
- The ResultSet class is the class having methods to store the output of the executed query. We created object of ResultSet class passing the query using Statement object and executeQuery() method.
- Finally the try..catch is used to find the catch any error like SQLException or ClassNotFoundException.
Java Program To Insert Value into Database/Table.
Reviewed by LanguageExpert
on
August 25, 2017
Rating:
No comments