SVXX

JDBC Prepared Statement

Sep 1st, 2013
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.57 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.*;
  3.  
  4. class DoPrepSQL
  5. {
  6.     Connection con;
  7.     PreparedStatement ps = null;
  8.     String updateName = "UPDATE PrepStudent SET StudentName=? where ID=?";
  9.     List<String> rightNames = new ArrayList<String>();
  10.     List<String> IDs = new ArrayList<String>();
  11.     public void ConnectToDB() throws SQLException, ClassNotFoundException
  12.     {
  13.         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  14.         String url = "jdbc:odbc:PrepStudentDSN";
  15.         con = DriverManager.getConnection(url, "", "");
  16.         con.setAutoCommit(false);
  17.         ps = con.prepareStatement(updateName);
  18.     }
  19.     public void PopulateNames()
  20.     {
  21.         rightNames.add("Vishal Agarwal");
  22.         rightNames.add("Mohit Sachdeva");
  23.         IDs.add("10-CS-1076");
  24.         IDs.add("10-CS-1094");
  25.     }
  26.     public void UpdateDetails() throws SQLException, ClassNotFoundException
  27.     {
  28.         ConnectToDB();
  29.         PopulateNames();
  30.         for(int i = 0; i < 2; i++)
  31.         {
  32.             ps.setString(1, rightNames.get(i));
  33.             ps.setString(2, IDs.get(i));
  34.             ps.executeUpdate();
  35.         }
  36.         con.commit();
  37.         if(ps != null)
  38.             ps.close();
  39.     }
  40. }
  41.  
  42. public class PreparedStateUse
  43. {
  44.     public static void main(String... args)
  45.     {
  46.         try
  47.         {
  48.             DoPrepSQL ds = new DoPrepSQL();
  49.             ds.UpdateDetails();
  50.         }
  51.         catch(Exception e)
  52.         {
  53.             System.err.println(e.toString());
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment