Pin It

How to perform create sql query in a Java application using JDBC ?



A simple Java application showing how to query a table in a database i.e performing a create query using JDBC

Steps for querying a Database using JDBC -

1. Download the driver jar from Internet and place it in classpath of your Java application. Here I am using MySql as Database so I have downloaded the jar with name as : "mysql-connector-java-5.1.20-bin.jar"

2. Create a Database (am using MySql as backend) name as "javaee".

3. Create a Java Class. It will perform necessary select query and output it to browser. The code for Java class is shown below -


package com.hubberspot.jdbc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class CreateJdbcQuery {

 Connection connection = null;
 ResultSet resultSet = null;
 Statement statement = null;
 String query = null;
 String url = null;
 String username = null;
 String password = null;

 public static void main(String[] args) {

  CreateJdbcQuery cjq = new CreateJdbcQuery();
  cjq.createConnection();
  cjq.executeQuery();

 }

 private void createConnection() {

  url = "jdbc:mysql://localhost:3306/javaee";
  username = "root"; 
  password = "root"; 
  try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();

   connection = DriverManager.getConnection(url, username , password);
  }
  catch (Exception e) {

   e.printStackTrace();
  }


 }

 private void executeQuery() {

  query = "create table user " +      
    "(First_Name varchar(20) NOT NULL,"+    
    "Last_Name varchar(30) NOT NULL,"+
    "Email varchar(50) NOT NULL,"+
    "City varchar(30) NOT NULL,"+    
    "password varchar(30) NOT NULL PRIMARY KEY "+    
    ");";
  
  try {
   
   statement = connection.createStatement();
   statement.execute(query);
            
  }
  catch (SQLException e) {

   e.printStackTrace();
  }
  finally {
   try {    
    statement.close();
    connection.close();
   }
   catch (SQLException e) {

    e.printStackTrace();
   } 
  }

 }

}




Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot