In order fo your JDBC to use sql queries, your program must understand it is a SQL command and not just random gibberish you are typing.
How would you use a statement command?
Statement statementName = connection.createstatement();
Statement is the interface;
statementName is the name of the statement you are creating;
connection.createstatement () – connection is the object and createstatement is the method.
Where is the Statement located?
You have to use the java.sql package in order to make use of the statement commands.
Methods in the Statements
- boolean execute(String sql)
- Return a true if the result is a ResultSet object and false if it is an update count or there are no results.
- ResultSet executeQuery(String sql)
- Returns results to the console. it only returns a single result object though. You can use a for loop for it return multiple results.
- int executeUpdate(String sql)
- Executes any of the DDL commands
- Returns an int denoting row count or returns 0 if nothing happens.
- BTW: This method cannot be called on a PreparedStatement or CallableStatement.
- int[] executeBatch()
- submit a bunch of commands to the database for execution and returns array of updated counts if executed successfully.
Example
package com.collabera.jdbc;
import java.sql.SQLException;
import java.sql.*;
import java.sql.DriverManager;
import java.sql.Connection;
public class ConnectionManager {
static final String URL = "jdbc:mysql://localhost:3306/testdb?serverTimezone=EST5EDT";
static final String USERNAME = "root";
static final String PASSWORD = "password";
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
System.out.println("Connection was made");
//Creating a Statement
Statement statement = conn.createStatement();
//------------------------------//
//--------execute method--------//
boolean flag = statement.execute("select * from table_name");
if(flag == false) {
System.out.println("Here are the rows" + statement.getUpdateCount());
}
//-----executeUpdate Method---------//
//-----Insert
int actorName = statement.executeUpdate("Insert into table_name(firstName,lastName) values ('Jake', 'Castle')");
System.out.println("Row Inserted and now the count is " + count);
//-----Update
count = statement.executeUpdate("Update table_name set firstName = 'Sai' where firstName = 'Sai Allala'");
System.out.println("Row Updated and now the count is " + count);
//-----delete
count = statement.executeUpdate("Delete from table_name where firstName = 'Sai'");
System.out.println("Row deleted and now the count is " + count);
}
catch(SQLException e){
e.printStackTrace();
}
return conn;
}
public static void main(String[] args) {
Connection conn = ConnectionManager.getConnection();
try {
conn.close();
System.out.println("Connection was closed");
}
catch(SQLException e) {
e.printStackTrace();
}
}
}
References
https://netjs.blogspot.com/2017/12/statement-interface-in-java-jdbc.html





