In this section you will learn how to create database using JDBC with example.
In this section you will learn how to create database using JDBC with example.In this section you will learn how to create database using JDBC with example.
Create Database :
Database is an organized collection of data. It is the easy way of accessing
,managing and updating the data.In Our discussion we are using MYSQL database.
It is Relational DBMS so we don't need to think how data is related and how to
get data from database. We store the data in the form of table.
For creation of database we need to understand some terms which are important in
creation of databse.
Connection: This interface specifies connection with specific databases like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of this interface.
Class.forName(String driver): It loads the driver.
DriverManager : The DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property
getConnection(String url, String userName, String password): This method establishes a connection to specified database url.
The MySQL connection URL has the following format:
jdbc:mysql://[host][:port]/[database][?property1][=value1]...
Statement: This interface executes the SQL statement and returns the result it produces.
createStatement(): It is a method of Connection interface which returns Statement object.
executeUpdate(String table): This method of Statement interface execute sql statements(insert or delete or update) which takes the sql query of string type and returns int.
Example : In this example we are creating database, named students.
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; class CreateDatabase{ public static void main(String[] args){ System.out.println("Database Creation Example!"); Connection conn = null; Statement statement=null; String url = "jdbc:mysql://localhost:3306/"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try{ Class.forName(driverName); conn = DriverManager.getConnection(url, userName, password); statement = conn.createStatement(); String sql = "CREATE DATABASE students"; statement.executeUpdate(sql); System.out.println("Database created successfully..."); conn.close(); }catch (Exception e) { e.printStackTrace(); } } }
Output :
Database Creation Example! Database created successfully...