Join us on Facebook

Please wait..10 Seconds Cancel

11.07.2013

// // Leave a Comment

Demonstration of Prepared Statement In Java

Prepared Statement


Sometimes it is more convenient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from the more general class, Statement, that you already know.
If you want to execute a Statement object many times, it usually reduces execution time to use a PreparedStatement object instead.
The main feature of a PreparedStatement object is that, unlike a Statement object, it is given a SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just a SQL statement, but a SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.
Although PreparedStatement objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.
import java.awt.*; 
import java.sql.*; 
import javax.swing.*; 
import java.awt.event.*; 
 
 
public class JdbcPrepared extends JFrame { 
  private static final long serialVersionUID = 1L; 
  private JPanel contentPane; 
  private JTextField textFieldName; 
  private JTextField textFieldSurname; 
   
  public static void main(String[] args) {   
    JdbcDemo frame = new JdbcDemo(); 
    frame.setVisible(true);   
   
  public JdbcPrepared() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    contentPane = new JPanel(); 
   
    setContentPane(contentPane); 
    contentPane.setLayout(null); 
     
    JLabel lblName = new JLabel("Name"); 
    contentPane.add(lblName); 
     
    textFieldName = new JTextField(); 
    contentPane.add(textFieldName); 
 
     
    JLabel lblSurname = new JLabel("Surname"); 
    contentPane.add(lblSurname); 
     
    textFieldSurname = new JTextField(); 
    contentPane.add(textFieldSurname); 
     
    JButton btnSubmit = new JButton("Submit"); 
    btnSubmit.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
        try { 
            Connection conn = getConnection(); 
               Statement st = conn.createStatement(); 
               System.out.println(conn.toString()); 
               String name=textFieldName.getText(); 
               String surname=textFieldSurname.getText(); 
               String str=""; 
               ResultSet rs; 
               PreparedStatement preparedStatement = 
conn.prepareStatement("INSERT INTO users (Name1,Surname1) VALUES (?,?)"); 
                    preparedStatement.setString(1,name); 
                    preparedStatement.setString(2,surname); 
                    preparedStatement.executeUpdate(); 
               str= "SELECT * FROM users"; 
               rs = st.executeQuery(str);  
               System.out.println(conn.toString()); 
                
            //get and displays the number of columns 
 
               ResultSetMetaData rsMetaData = 
rs.getMetaData(); 
            int numberOfColumns = 
rsMetaData.getColumnCount(); 
               System.out.println("resultSet MetaData column 
Count=" + numberOfColumns); 
               while (rs.next())  
                      { 
                      for (int i = 1; i <= numberOfColumns; i++)  
                           { 
                               if (i > 1) 
                              System.out.print(", ");                             
                              String columnValue = rs.getString(i); 
                              System.out.print(columnValue); 
                           } 
                       System.out.println(""); 
                       } 
               st.close(); 
               conn.close(); 
           } catch(Exception e) { 
            System.out.println(e.getMessage()); 
           } 
          } 
    }); 
    contentPane.add(btnSubmit); 
  } 
   
  public static Connection getConnection() { 
       String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; 
          String url = "jdbc:odbc:testDb";  
          String username = ""; //leave blank if none 
          String password = ""; //leave blank if none 
          try { 
        Class.forName(driver); 
       } catch (ClassNotFoundException e) { 
         System.out.println(e.toString()); 
       } 
          try { 
        return DriverManager.getConnection(url, username, password); 
       } catch (SQLException e) { 
         System.out.println(e.toString()); 
       } 
       return null; 
      } 
} 

0 comments:

Post a Comment