Inserting values in MySQL database table

After making the table in the database, we need to
insert the values in the database. Here we are going to see, how we can insert values in
the MySQL database table. We know that tables store data in rows and
column format. After creating a database table, you need to insert the values in it. In
this section, we are providing an example with code that provides the facility
for inserting the values in MySQL database table.
Description of program:
First of all this program establishes the connection
with MySQL database through the JDBC driver, after only that we will be
able to insert the values in
specific table with the help of some APIs and methods. If any values get
inserted in the table then shows a message "1 row affected" but
if any problems comes while inserting the data in the table then it will displays
the message "SQL statement
is not executed!".
Description of code:
INSERT table_name VALUES(field_values):
Above code is used, when you want to insert values in the database table
with appropriate value.
Here is the code of program:
import java.sql.*;
public class InsertValues{
public static void main(String[] args) {
System.out.println("Inserting values in Mysql database table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db,"root","root");
try{
Statement st = con.createStatement();
int val = st.executeUpdate("INSERT employee VALUES("+13+","+"'Aman'"+")");
System.out.println("1 row affected");
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
|
Download this example.
Output of program:
C:\vinod\jdbc\jdbc\jdbc-mysql>javac
InsertValues.java
C:\vinod\jdbc\jdbc\jdbc-mysql>java InsertValues
Inserting values in Mysql database table!
1 row affected |

|