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();
}
}
}
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
Retrieving All Rows from a Database Table
Here, you will learn how to retrieve all rows from a database table. You know that table contains the data in rows and columns format. If you want to access the data from a table then you need to use some APIs and methods. See brief descriptions for retrieving all rows from a database table as below:
Description of program:
Program establishes the connection between MySQL database and java file so that the we can retrieve all data from a specific database table. If any exception occurs then shows a message "SQL code does not execute.".
Description of code:
executeQuery(String sql):
This method executes the SQL statement and returns a single ResultSet object. It takes string type parameter for executing the SQL statement.
SELECT * FROM table_name:
Above code retrieves all data from specific database table.
getInt(String column_name):
This method is of java.sql.ResultSet interface that takes string type parameter and returns an integer type values.
getString(String column_name):
This method is same as getInt() method but it returns the string type values.
Here is the code of program:
import java.sql.*;
public class GetAllRows{
public static void main(String[] args) {
System.out.println("Getting All Rows from a table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employee6");
System.out.println("Emp_code: " + "\t" + "Emp_name: ");
while (res.next()) {
int i = res.getInt("Emp_code");
String s = res.getString("Emp_name");
System.out.println(i + "\t\t" + s);
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Output of program:
C:\vinod\jdbc\jdbc-mysql>java GetAllRows
Getting All Rows from a table!
Emp_code: Emp_name:
10 vinod
11 Amar
15 Aman
1 sushil
Count Rows from a Database Table
After creating a database table, if we want to know number of rows in a table then we can get it very easily by using the simple database query. See brief description below:
Description of program:
For this program to work firstly we need to establish the connection with MySQL database by the help of JDBC driver. When the connection has been established we need to pass a table name from the given database in the query and the rows will be counted and the result will be displayed. If any exception is thrown then it will show "SQL statement is not executed!"
Description of code:
SELECT COUNT(*) FROM table_name;
This code is used to count the rows of given table.
table_name: It is a name of the table of which we want to see the rows.
Here is the code of program:
import java.io.*;
import java.sql.*;
public class CountRows{
public static void main(String[] args) {
System.out.println("Count number of rows in a specific table!");
Connection con = null;
int count = 0;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter table name:");
String table = bf.readLine();
ResultSet res = st.executeQuery("SELECT COUNT(*) FROM "+table);
while (res.next()){
count = res.getInt(1);
}
System.out.println("Number of column:"+count);
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
output of program:
C:\vinod\jdbc\jdbc\jdbc-mysql>javac CountRows.java
C:\vinod\jdbc\jdbc\jdbc-mysql>java CountRows
Count number of rows in a specific table!
Enter table name:
student
Number of column:6
Getting Column Names from a database table in Java
Here we are providing you an example with code that retrieves all columns name in a specific database table. Sometimes, you need to know the number of columns and the names of the columns of the table, so you can retrieve it with the help of this example. See detail information given below:
Description of program:
Create a class ColumnName. The name of the class should be such that the other person can easily understand what this program is going to do. Strictly follow the naming conventions of java. Now declare a static method inside which creates the connection with MySQL database through the JDBC driver. After establishing the connection then you get all columns name and number of columns of specified table with the help of some APIs and methods.
Description of code:
ResultSetMetaData:
This is an interface of java.sql package that can be used for getting information about types and properties of columns in a ResultSet object.
getColumnCount():
Above method retrieves number of columns (integer types data) in the ResultSet object.
getColumnName(int column):
This method returns columns name (string type data) from ResultSetMetaData object and takes integer type value.
Here is the code of program:
import java.sql.*;
public class ColumnName{
public static void main(String[] args) {
System.out.println("Getting Column Names Example!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM employee6");
ResultSetMetaData md = rs.getMetaData();
int col = md.getColumnCount();
System.out.println("Number of Column : "+ col);
System.out.println("Columns Name: ");
for (int i = 1; i <= col; i++){
String col_name = md.getColumnName(i);
System.out.println(col_name);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Output of program:
C:\vinod\jdbc\jdbc-mysql>javac ColumnName.java
C:\vinod\jdbc\jdbc-mysql>java ColumnName
Getting Column Names Example!
Number of Column : 2
Columns Name:
Emp_code
Emp_name
Adding a New Column Name in Database Table
In this jdbc tutorial program we are going to learn about adding a new column in database table. Sometimes it happens that we have created a table and forgets to add some important column name into it. Later while retrieving the data from that table we come to know that the table doesn't contains that particular column we are searching for. So there is no need to get panic. We have the solution for this, we are describing it with the help of the simple example. Brief description given below:
Description of program:
Firstly we need to create a connection with the help of JDBC driver for connecting to the MySQL database. Remember, in this program we are going to add columns to an existing database table. After establishing the connection, it takes table name, column name and it's data type and at last add a new column in the table. If the column gets inserted or added in the table then it shows "Query OK, n rows affected" otherwise it will displays a message "Table or column or data type is not found!".
Description of code:
ALTER TABLE table_name ADD col_name data_type;
Above code is used for adding a new column in the database table and takes appropriate attributes:
table_name: This is a table name in which you want to add a new column name.
col_name: It is a name of the column that you want to add in a table.
data_type: This is a data type of new column.
Here is the code of program:
import java.io.*;
import java.sql.*;
public class AddColumn{
public static void main(String[] args) {
System.out.println("Adding new column in table example!");
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/jdbctutorial","root","root");
try{
Statement st = con.createStatement();
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter table name:");
String table = bf.readLine();
System.out.println("Enter column name:");
String col = bf.readLine();
System.out.println("Enter data type:");
String type = bf.readLine();
int n = st.executeUpdate("ALTER TABLE "+table+" ADD "+col+" "+type);
System.out.println("Query OK, "+n+" rows affected");
}
catch (SQLException s){
System.out.println("Tabel or column or data type is not found!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
Database Table: Student Table
Stu_id Stu_name Stu_sub
100 vinod computer
101 raju math
102 ranjan bio
103 Aman phy
Output of program:
C:\vinod\jdbc\jdbc\jdbc-mysql>javac AddColumn.java
C:\vinod\jdbc\jdbc\jdbc-mysql>java AddColumn
Adding new column in table example!
Enter table name:
Student
Enter column name:
Stu_marks
Enter data type:
integer
Query OK, 4 rows affected
After adding a new column: Student Table
Stu_idl Stu_name Stu_sub Stu_marks
100 vinod computer NULL
101 raju math NULL
102 ranjan bio NULL
103 Aman phy NULL
No comments:
Post a Comment