Advertisement
Mark2020H

How to JDBC with MariaDB example

Feb 8th, 2020
618
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.71 KB | None | 0 0
  1. /*Notes for others before you try this  You must grant all permission to root as follows otherwise this will not work
  2. At command prompt to enter MySQL  type the following  mysql -u root -p
  3. This will  request password from you  and if successful you should see the following
  4. as prompt
  5.  
  6. MariaDB [(none)]>
  7.  
  8. At this prompt type the following below
  9. GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'your password here';  ## now hit enter key
  10.  
  11. You should  have returned  this below or similar
  12. Query OK, 1 rows affected (0.03 sec)  
  13.  
  14. Now at the same prompt type like so  then hit the enter key
  15. MariaDB [(none)]> quit
  16.  
  17. MD Harrington  23:42Hrs Saturday 8th February 2020
  18.  
  19. */
  20. package mariadb;
  21.  
  22.  
  23. import java.sql.Connection;
  24. import java.sql.DriverManager;
  25. import java.sql.ResultSet;
  26. import java.sql.ResultSetMetaData;
  27. import java.sql.SQLException;
  28. import java.sql.Statement;
  29. import java.util.Properties;
  30. import java.util.logging.Level;
  31. import java.util.logging.Logger;
  32.  
  33. public class SimpleJDBCApplication {
  34.     // JDBC driver name and database URL
  35.  
  36.     static final String JDBC_DRIVER = "org.mariadb.jdbc.Driver";
  37.     static final String DB_URL = "jdbc:mariadb://localhost/Business";
  38.  
  39.     //  Database credentials
  40.    final String USER = "root";
  41.    final String PASS = "xxxxx"; // Dont forget to put your password in here
  42.    
  43.     private Statement stmt = null ;
  44.     private ResultSet rs ;
  45.    
  46.     private Properties props ;
  47.  
  48.     public SimpleJDBCApplication() {
  49.        
  50.         props = new Properties();
  51.         props.put(this.USER,USER);
  52.         props.put(this.PASS,PASS) ;
  53.       }
  54.    
  55.     public Connection getConnection()
  56.     {
  57.         Connection conn = null ;
  58.        
  59.        
  60.          System.out.println("Connecting to a selected database...");
  61.         try {
  62.             conn = DriverManager.getConnection(
  63.                     DB_URL, props.getProperty(USER), props.getProperty(PASS));
  64.         } catch (SQLException ex) {
  65.             Logger.getLogger(SimpleJDBCApplication.class.getName()).log(Level.SEVERE, null, ex);
  66.         }
  67.             System.out.println("Connected database successfully...");
  68.        
  69.         return conn ;
  70.     }
  71.    
  72.    
  73.     public void executesql(Connection con , String sqlcommand){
  74.  
  75.         try {
  76.            
  77.             stmt = con.createStatement();
  78.  
  79.             stmt.executeUpdate(sqlcommand);
  80.            
  81.             System.out.println("Sql Success in given database...");
  82.            
  83.            
  84.                     } catch (SQLException ex) {
  85.             Logger.getLogger(SimpleJDBCApplication.class.getName()).log(Level.SEVERE, null, ex);
  86.         } finally {
  87.             //finally block used to close resources
  88.             try {
  89.                 if (stmt != null) {
  90.                     stmt.close();
  91.                 }
  92.             } catch (SQLException se) {
  93.             }// do nothing
  94.             try {
  95.                 if (con != null) {
  96.                     con.close();
  97.                 }
  98.             } catch (SQLException se) {
  99.                 // deal with sql exceptions here
  100.                
  101.             }//end finally try
  102.         }//end try
  103.        
  104.        
  105.     }
  106.    
  107.    
  108.     public void retrieveData(Connection con , String sql)
  109.     {
  110.  
  111.         try {
  112.             stmt = con.createStatement();
  113.             rs = stmt.executeQuery(sql);
  114.            
  115.  
  116.             // how to get the Max column count in your table  
  117.  
  118.             ResultSetMetaData rsmd = rs.getMetaData();
  119.  
  120.             // this returns number of coloumbs in your table you created
  121.             int numCols = rsmd.getColumnCount();
  122.            
  123.             /*Print the data to the console rs RS  or your record set contains the number of columns for matching
  124.             records  */
  125.  
  126.    
  127.             while(rs.next()){
  128.                
  129.                 /*  Iterate through each column */
  130.                 /* Since I know that my table uses only VARCHAR type I need only use rs,GetString() method */
  131.  
  132.                 for(int i= 1 ; i <=numCols ; i++ )
  133.                 {                
  134.                 System.out.print("|" rs.getString(i) + "|" "\t" );
  135.                 }
  136.                 System.out.println(""); // add  a line  after printing this in tabbed format
  137.             }
  138.         } catch (SQLException ex) {
  139.             Logger.getLogger(SimpleJDBCApplication.class.getName()).log(Level.SEVERE, null, ex);
  140.         }finally {
  141.             //finally block used to close resources
  142.             try {
  143.                 if (stmt != null) {
  144.                     stmt.close();
  145.                 }
  146.             } catch (SQLException se) {
  147.             }// do nothing
  148.             try {
  149.                 if (con != null) {
  150.                     con.close(); // always close the connection  
  151.                 }
  152.             } catch (SQLException se) {
  153.                 // deal with sql exceptions here
  154.                
  155.             }
  156.         } //end finally try  
  157.  
  158.     }
  159.    
  160.    
  161.     public static void main(String[] args) {
  162.  
  163.         SimpleJDBCApplication myApp ; //  set aside your memory location for this object
  164.         String sql ;  // for holding your sql commands
  165.  
  166.         myApp = new SimpleJDBCApplication() ; // create a new instance
  167.  
  168.        // create table
  169.  
  170.               sql = "CREATE TABLE IF NOT EXISTS CONTACTS" +
  171.                    "(" +
  172.                    " ClientId VARCHAR(30) not NULL, " +
  173.                    " First_name VARCHAR(30), " +
  174.                    " Last_Name VARCHAR(30), " +
  175.                    " Telephone VARCHAR(30), " +
  176.                    " Mobile VARCHAR(30), " +
  177.                    " Email VARCHAR(40), " +
  178.                    " PostCode VARCHAR(50), " +
  179.                    " PRIMARY KEY (ClientId)" +                    
  180.                    ")";
  181.        
  182.           myApp.executesql(myApp.getConnection(), sql); // invoke the method calls on your my App object
  183.        
  184.          // this will only run once  due to  using unique key    You cannot have tow or more records with same ID
  185.  
  186.               sql = "INSERT INTO Business.CONTACTS " +
  187.                     "(ClientId, First_name, Last_Name, Telephone, Mobile, Email, PostCode) "+                      
  188.                 "VALUES ('HAR1234', 'Mark', 'Harrington', '0208 8218564', '07234 123123', 'someone@hotmail.com', 'BR3 3PZ')" ;
  189.          
  190.              
  191.           myApp.executesql(myApp.getConnection(), sql);
  192.  
  193.  // check to see if your table was populated with above data
  194.          
  195.               sql = "SELECT * From  Business.CONTACTS " ;
  196.              
  197.           myApp.retrieveData(myApp.getConnection(), sql);
  198.  
  199.         System.out.println("Goodbye! \n From Main Method  \n Now you can start  creating a GUI to do this for you");
  200.     }//end main
  201. }//end JDBCExample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement