JDBC Program Using MySQL



    import java.sql.*;
    public class SampleMySQlProgram {
       public static void main(String[] args) {
        Connection conn = null; //Connection is use for connecting java and mysql
       Statement stmt = null; // use to execute mysql query into java app    String url = null;    try
    {

        //create connection
          Class.forName("com.mysql.jdbc.Driver");
        /*url =jdbc:mysql://<localhostname>:<portNumber>/databaseName*/       url = "jdbc:mysql://localhost:3306/databaseName";       conn = DriverManager.getConnection(url,"root",""); 
        /* if you are using another user change (url,"root","")  into (url"username","yourpassword")*/ 
           stmt = conn.createStatement();
         
        //execute mysql query in this example i just use insert       stmt.executeUpdate("insert into tbltest(id,name)values('001','userAccount')");      
       // get record from mysql and display it.       ResultSet dsply = stmt.executeQuery("select * from tbltest");
        //loops until ther is no next from record.
         while(dsply.next()){
              int IDNO = dsply.getInt("ID"); //get record from ID field           String Name = dsply.getString("Name"); //get record from Name field           System.out.print(" IDNO: "+IDNO); // display ID           System.out.print(" Name: "+Name); //display Name           System.out.println(); //print next line       }    }catch(Exception e){
          e.printStackTrace();
       }  } }


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email