Pages

Wednesday, December 26, 2012

Connect Java Applications to Mysql Database in Ubuntu Using Netbeans IDE

Ubuntu Terminal

  1. Install Mysql Server and Mysql Client from Ubuntu Software Center
  2. Install JDBC Connector by typing in the terminal
    sudo apt-get install libmysql-java
  3. Check if can connect to mysql by typing
    mysql -u root -p
  4. Create required database and tables. For ex: create a database called newyear and table called party with fields id and name

Netbeans IDE

  1. Create a Java project/application in Netbeans
  2. In the main .java file add lines similar to this and save
    
    package javaapplication6;
    import java.sql.*;
    
    public class JavaApplication6 {
        
        private static final String url = "jdbc:mysql://localhost/newyear";
        private static final String user = "root";
        private static final String password = "";
            
        public static void main(String[] args) {
            System.out.println("Hello world!!");
            Statement stmt = null;
            try {
                    Connection con = DriverManager.getConnection(url, user, password);
                    System.out.println("Success");
                    stmt = con.createStatement();
                    String sql = "INSERT INTO party " + "VALUES (1, 'joe')";
                    stmt.executeUpdate(sql);
    
            } catch (Exception e) {
                    e.printStackTrace();
            }        
            
        }
    }
    
  3. Then right click on the project/application in the project explorer and click on Properties
  4. In the project properties window, select libraries tab. Then click on Add Jar/Folder button
  5. Select mysql.jar from /usr/share/java directory and then click on Ok
  6. Now save and run the project/application and check for output in the panel

Ubuntu Terminal

  1. To check if the record is inserted, type:
    mysql -u root -p
    show databases;
    use newyear;
    show tables;
    select * from party;
    

Note: Just hit an enter if no password is to be set when prompted.

No comments: