
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create a Table in JavaDB Using JDBC
You can create a table in JavaDB database using the CREATE TABLE statement.
Syntax
CREATE TABLE table_name ( column_name1 column_data_type1 constraint (optional), column_name2 column_data_type2 constraint (optional), column_name3 column_data_type3 constraint (optional) );
To create a table in JavaDB using JDBC API you need to −
- Register the driver − The forName() method of the class, Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method.
- Establish a connection − Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.
- Create Statement − Create a Statement object using the createStatement() method of the Connection interface.
- Execute the Query − Execute the query using the execute() method of the Statement interface.
Following JDBC program establishes connection with JavaDB database and creates a table named customers in it.
Example
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class CreatingTable { public static void main(String args[]) throws Exception { //Registering the driver Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); //Getting the Connection object String URL = "jdbc:derby:sampledatabase;create=true"; Connection conn = DriverManager.getConnection(URL); //Creating the Statement object Statement stmt = conn.createStatement(); //Query to create a table in JavaDB database String query = "CREATE TABLE Employee_data( " + "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, " + "Name VARCHAR(255), " + "Salary INT NOT NULL, " + "Location VARCHAR(255), " + "PRIMARY KEY (Id))"; //Executing the query stmt.execute(query); System.out.println("Table created"); } }
Output
Connection established...... Table Created......
Advertisements