Today, we will take an overview look of how to execute sql commands in Java. First will look at what sql commands are and then how to execute these command in Java using the Java database connectivity [JDBC]
SQL Commands
SQL commands are just instructions which are used to communicate with the database to perform a specific tasks. A few examples of these task are creating table (using the command CREATE), deleting table(using the command DELETE), and select.
SQL commands are grouped into four categories
Data Definition Language [DDL]
DDL are a group of sql commands which are used to create, modify and dropping a database structure
DDL commands
- create
- alter
- drop
- rename
- truncate
Data Manipulation Language [DML]
DML are a group of sql commands which are used for storing, retrieving, modifying, and deleting data
DML commands
- select
- insert
- update
- delete
Transaction Control Language [TCL]
TCL are a group of sql commands which are used for managing changes affecting the data [think of it like git]
TCL commands
- commit
- rollback
- savepoint
Data Control Language [DCL]
DCL are a group of sql commands which are used for managing changes affecting the data
DCL commands
- grant
- revoke
Steps to execute SQl command in Java using JDBC API with code examples
First establish a connection with the database
conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
Use the connection object to create an sql statement object
Statement statement = conn.createStatement();
statement is representation of an sql statement. statement is an interface that defines method for executing method
use execute methods from statement object to execute a query
//create a table
statement.executeUpdate(sqlCommandToCreateTable);
Resources
- https://beginner-sql-tutorial.com/sql-commands.htm
- https://beginner-sql-tutorial.com/sql-group-functions.htm
- https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html#creating_statements
- https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html
- https://coderwall.com/p/609ppa/printing-the-result-of-resultset
github link to full program – https://github.com/AbePierrot/Execute-SQL-Statement-In-Java