JDBC Statement Example


 

JDBC Statement Example

In this tutorial you will learn java.sql.Statement interface and also how to use this interface in your application.

In this tutorial you will learn java.sql.Statement interface and also how to use this interface in your application.

JDBC Statement

JDBC Statement is an interface of java.sql.*; package. It is used for execution of SQL statements. It returns a ResultSet object. This result set object contains the result of the query. Statement interface provides basic method for SELECT, INSERT, UPDATE, DELETE operations in the database. Its query is compiled every time when request is made, therefore is little slower in comparison to PreparedStatement.

An example given below which illustrate to JDBC Statements interface. This example creates a table named StudentDetail in student database.

At first create a database in MySlq named student.

JDBCStatementExample.java

package roseindia.net;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementExample {
	Connection connection = null;

	public JDBCStatementExample() {
		try {
			// Loading the driver
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println(e.toString());
		}
	}

	public Connection createConnection() {
		Connection con = null;
		if (connection != null) {
			System.out.println("Cant create a connection");
		} else {
			try {
				// Crating a Connection to the Student database
				con = DriverManager.getConnection(
						"jdbc:mysql://localhost:3306/student", "root",
						"root");
				System.out.println("Connection created Successfully");
			} catch (SQLException e) {
				System.out.println(e.toString());
			}
		}
		return con;
	}

	public static void main(String[] args) throws SQLException {
		JDBCStatementExample jdbccOnnectionExample = new JDBCStatementExample();
		Connection conn = jdbccOnnectionExample.createConnection();
		// Creating a Statement reference variable
		Statement stmt = null;
		// getting the connection reference to the Statement
		// Creating a statement
		stmt = conn.createStatement();
		String queryString = "CREATE TABLE StudentDetail (RollNo int(9)  PRIMARY KEY NOT NULL, Name tinytext NOT NULL,Course varchar(25) NOT NULL, Address text  );";
		// Executing query
		stmt.executeUpdate(queryString);
		System.out.println("Table created successfully............");
		stmt.close();
		conn.close();
	}
}

When you run this application it will display message as shown below:


Connection created Successfully
Table created successfully............

Download this example code

Ads