If we need to insert some record into a database table from our java application,the JDBC API provides ways to insert into database in Java . Here we are explaining the concept with help of suitable example.
We are using MySQL server 5.6 . The free version of MySQL is available here.
Now login to the MySQL either from the command line client or from the SQLyog .
For inserting a record to database table we need to have a database in our newly installed MySQL environment. Also there should be one database table to store it.Let us create these things first.
The queries given below creates a database with name testdb and table testtable.The table testtable is having two columns:number(of type int) and data(of type varchar).
Now let us see the code.For this code we should put the MySQL connector jar in class path (The jar contains the driver and other components for connecting with MysQL database).We can download the MySQL connector jar from here.
The line starts with class.forName() loads the driver class for connecting with MySQL server. Then a connection is establishing and executing the update task. Then iterating the table for getting the contents. If we run the code only once, we will get the output. If we try to run more times exception will be thrown.Because database is not allowing the duplication primary key value. (We defined the field number as primary key while creating the table).