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 −