Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insert record in a MySQL table with Java
Let us first create a table. Following is the query to create a table in MySQL −
mysql> create table DemoTable( Id int, Name varchar(30), CountryName varchar(30), Age int ); Query OK, 0 rows affected (0.66 sec)
Following is the Java code to access MySQL database −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
public class AccessMySQLDatabase {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc :mysql ://localhost :3306/web?" + "useSSL=false", "root", "123456");
st = con.createStatement();
String accessDatabase = "insert into DemoTable(Id,Name,CountryName,Age)" + " values(100,'David','AUS',24) ";
int result = st.executeUpdate(accessDatabase);
if (result > 0) {
System.out.println("Record Inserted! Check your table now!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This will produce the following output −
Record Inserted! Check your table now!
Let us now check the MySQL table −
Mysql> select * from DemoTable;
This will produce the following output −
+------+-------+-------------+------+ | Id | Name | CountryName | Age | +------+-------+-------------+------+ | 100 | David |AUS | 24 | +------+-------+-------------+------+ 1 row in set (0.00 sec)
Following is the snapshot of records inserted using Java −

Advertisements