Advertisement
Guest User

JDBC

a guest
Apr 14th, 2016
706
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1. import com.mysql.jdbc.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7.  
  8.  
  9. public class SqlTest {
  10.  
  11.    
  12.     public static void main(String[] args) throws ClassNotFoundException, SQLException {
  13.         Class.forName("com.mysql.jdbc.Driver");
  14.        
  15.         // connecting to the database
  16.         java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://db4free.net:3306/database_name?useSSL=false", "username","password");
  17.    
  18.            // how to read from the database
  19.         PreparedStatement state = con.prepareStatement("select * from student");
  20.        
  21.         // Resultset takes the data as a iterable array
  22.         ResultSet result = state.executeQuery();
  23.        
  24.         System.out.println("\n reading from the database \n");  
  25.        
  26.         // iterable resultset is printed
  27.         // result.getString(1) implies first column and each loop represents a row
  28.         while(result.next()){
  29.             System.out.println(result.getString(1)+"   "+result.getString(2)+"  " + result.getString(3));
  30.         }
  31.        
  32.        
  33.         // how to write to the database
  34.         Statement stmt = con.createStatement();
  35.        
  36.         // ususal SQL commands as Strings
  37.         stmt.executeUpdate("INSERT INTO student " +
  38.                    "VALUES (2354,'Nimal','Perera')");
  39.        
  40.         result = state.executeQuery();
  41.        
  42.         System.out.println("\nAfter writing to the database \n");  
  43.        
  44.         while(result.next()){
  45.             System.out.println(result.getString(1)+"   "+result.getString(2)+"  " + result.getString(3));
  46.         }
  47.        
  48.     }  
  49.    
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement