WHAT'S NEW?
Loading...

This code performs CRUD Operation which allows applications to add a new records, retrieve, update, and delete. This includes basic profile information such as first name, last name, and gender. However, you can add more information if you like.

Global variable.

String connectionString;

OleDbConnection conn;

OleDbDataAdapter da;

OleDbCommand cmd;

//DataSet ds;

string sql;

public int x;

I created method dbConnection that point to my database location which located to my documents

public void dbConnection()

        {

 

            connectionString = @"Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\\Users\Juno\Documents\dbInformation.mdb";

            conn = new OleDbConnection(connectionString);

            conn.Open();

            //MessageBox.Show("Connection Open  !");

            //conn.Close();

        }

Note: In a creating your database, if you are using old version .mdb is the right format otherwise .accdb for newer version. For more info, visit this link: https://www.connectionstrings.com/access/

Again, I create another method retrieveALL that will retrieve all records stored in database.

private void retrieveALL(){

             dbConnection();

            sql = "SELECT * FROM tblProfile";

            da = new OleDbDataAdapter(sql, conn);

            DataTable dt = new DataTable();      //ds = new DataSet();

            da.Fill(dt);                         //da.Fill(ds, "dbInformation");

            dataGridView1.DataSource = dt;       //dataGridView1.DataSource = ds.Tables[0];

            conn.Close();

        }

Save button that will save new added records.

private void btnSave_Click(object sender, EventArgs e)

        {

 

            dbConnection();

            sql = "INSERT INTO tblProfile (Firstname,Lastname,Gender) VALUES ('" + txtFname.Text + "','" + txtLname.Text + "','" + cbGender.Text + "')";

            cmd = new OleDbCommand(sql, conn);

            cmd.ExecuteNonQuery();

            MessageBox.Show("Successfully Added to your Database", "New Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);

            conn.Close();

 

            //btnReadDatabase_Click(sender, e);

            retrieveALL();

        }

DataGridview allows display all stored records in database. To initiate the code, go to datagridview click event and choose cellDoubleClick. So when the users double click the cell, it will display current rows index.

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)

        {

           

            x = dataGridView1.Rows.IndexOf(dataGridView1.CurrentRow);

 

            txtFname.Text = dataGridView1.Rows[x].Cells[1].Value.ToString();

            txtLname.Text = dataGridView1.Rows[x].Cells[2].Value.ToString();

            cbGender.Text = dataGridView1.Rows[x].Cells[3].Value.ToString();

            MessageBox.Show(dataGridView1.Rows[x].Cells[0].Value.ToString());

 

        }

To update new records. The following codes initiate in update button.

private void btnUpdate_Click(object sender, EventArgs e)

        {

            dbConnection();

            int indexID;

            x = dataGridView1.Rows.IndexOf(dataGridView1.CurrentRow);

            indexID =  Convert.ToInt32((dataGridView1.Rows[x].Cells[0].Value.ToString()));

 

            sql = "UPDATE tblProfile SET Firstname= '" + txtFname.Text + "',Lastname='" + txtLname.Text +

                "',Gender='" + cbGender.Text + "' WHERE ID=" + indexID + "";

 

            cmd = new OleDbCommand(sql, conn);

            cmd.ExecuteNonQuery();

            MessageBox.Show("Successfully Updated...", "Update");

            conn.Close();

 

            //btnReadDatabase_Click(sender, e);

            retrieveALL();

        }

To delete records.

private void btnDelete_Click(object sender, EventArgs e)

        {

            dbConnection();

            int indexID;

            x = dataGridView1.Rows.IndexOf(dataGridView1.CurrentRow);

            indexID = Convert.ToInt32((dataGridView1.Rows[x].Cells[0].Value.ToString()));

 

            sql = "DELETE FROM tblProfile WHERE ID=" + indexID + "";

 

            cmd = new OleDbCommand(sql, conn);

            cmd.ExecuteNonQuery();

            MessageBox.Show("Successfully Deleted...", "Delete");

            conn.Close();

            retrieveALL();

        }

To search records.

private void btnSearch_Click(object sender, EventArgs e)

        {

            dbConnection();

            sql = "SELECT * FROM tblProfile WHERE Firstname='" + txtSearch.Text+ "' OR Lastname='" + txtSearch.Text +"'";

            da = new OleDbDataAdapter(sql, conn);

            DataTable dt = new DataTable();      //ds = new DataSet();

            da.Fill(dt);                         //da.Fill(ds, "dbInformation");

            dataGridView1.DataSource = dt;       //dataGridView1.DataSource = ds.Tables[0];

            conn.Close();

        }

 

To load records upon opening your application.

private void Form1_Load(object sender, EventArgs e)

        {

            dataGridView2.Columns.Add("Firstname","fname");

            dataGridView2.Columns.Add("Lastname","lname");

            dataGridView2.Columns.Add("Gender","gender");

            retrieveALL();

        }

Clear all textbox after adding records.

private void btnClear_Click(object sender, EventArgs e)

        {

            txtFname.Clear();

            txtLname.Clear();

            txtSearch.Clear();

            cbGender.Text = null;

        }

 

If you are going to add multiply entry instead adding one at a time in textbox. This work in in datagridview. The following codes shows how to add multiple records in datagridview and save it to database.

private void btnSaveALL_Click(object sender, EventArgs e)

        {

 

           

            for (int i = 0; i < dataGridView2.Rows.Count; i++)

            {

                sql = @"INSERT INTO tblProfile (Firstname,Lastname,Gender) VALUES ('"

                    + dataGridView2.Rows[i].Cells["Firstname"].Value + "',' "

                    + dataGridView2.Rows[i].Cells["Lastname"].Value + "', '"

                    + dataGridView2.Rows[i].Cells["Gender"].Value + "')";

                dbConnection();

                cmd = new OleDbCommand(sql, conn);

                cmd.ExecuteNonQuery();

 

                MessageBox.Show("Successfully Added to your Database", "New Record Added", MessageBoxButtons.OK, MessageBoxIcon.Information);

                conn.Close();

 

                //btnReadDatabase_Click(sender, e);

                retrieveALL();

            }

        }

 


The user will input the list of numbers and print the highest in java

int counter = 1;
        int number;
        int limit=0;
        int largest = 0;

        Scanner input = new Scanner(System.in);

        System.out.println("Enter limit number");
        limit = input.nextInt();

        System.out.println("Enter the number: ");
        number = input.nextInt();

        while(counter < limit)
        {
            System.out.println("Enter the number: ");
            number = input.nextInt();

            if(largest < number) {
                largest = number;
            }
            counter++;
        }
        System.out.println("The largest number is " + largest);
    }

The user will input the list of number and print the total sum.

 int sum=0,val,n,i;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter number of data points:");
        n=sc.nextInt();
        for(i=0;i<n;i++){
           System.out.print("Values "+i+":");
           val=sc.nextInt();
           sum+=val;
          }
        System.out.println("Total:"+sum);
    }
    static void message(String myText){
        System.out.println(myText);
    } 
The program will ask the user to enter the numbers and then will get the total sum and average inputted.

static Scanner scan = new Scanner (System.in);
    public static void main(String[]args){
        int limit=0;
        int number=0;
        int counter=0;
        int sum=0;
        message("Enter how many times");
        limit = scan.nextInt();
        while (counter<limit){
            message("Please enter the following numbers");
            number = scan.nextInt();
            sum += number;
            counter++;
        }
        System.out.println(sum);
    }
    static void message(String myText){
        System.out.println(myText);
    }   

with methods

static Scanner scan = new Scanner (System.in);
    static int sum=0;
    public static void main(String[]args){     
        int limit=0;
        int number=0;
        int counter=0;     
        message("Enter how many times");
        limit = scan.nextInt();
        while (counter<limit){
            message("Please enter the following numbers");
            number = scan.nextInt();
            getSum(number);
            counter++;
        }
        /* you can use the following loops below...
        do{
            counter++;
            message("Please enter the following numbers");
            number = scan.nextInt();
            getSum(number);  
        }while (counter<limit);

        for (counter=0;counter<limit;counter++){
            message("Please enter the following numbers");
            number = scan.nextInt();
            getSum(number);  
        } */
        message("Total Sum is equals to " + sum);
        message("Total Avearage is equals to " + sum/counter);
    }
    static void message(String myText){
        System.out.println(myText);
    } 
    static void getSum(int num){
        sum += num;
    }


       A prime number is a number which is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.

The following source code implements different ways in finding a prime numbers.

Source code: 

<option 1>


public static void main(String[]args){
        int num = 29;
        boolean flag = false;
        for(int i = 2; i <= num/2; ++i)
        {
            // condition for nonprime number
            if(num % i == 0)
            {
                flag = true;
                break;
            }
        }
        if (!flag)
            System.out.println(num + " is a prime number.");
        else
            System.out.println(num + " is not a prime number.");
    }
    

<option 2 using methods>



public static void main(String args[]){    
        checkPrime(1);  
        checkPrime(3);  
        checkPrime(17);  
        checkPrime(20);  
    }  
      static void checkPrime(int n){  
        int i,m=0,flag=0;      
        m=n/2;      
        if(n==0||n==1){  
         System.out.println(n+" is not prime number");      
        }else{  
         for(i=2;i<=m;i++){      
          if(n%i==0){      
           System.out.println(n+" is not prime number");      
           flag=1;      
           break;      
          }      
         }      
         if(flag==0)  { System.out.println(n+" is prime number"); }  
        }//end of else  
    }  

Lastly:

    public static void main(String[]args){
        get(10);   
    }
    static void get(int n){
        for (int x=0; x<=n; x++){
            for (int j=2; j<x; j++){
                if (x%j==0){
                    message(x +" is not a Prime number, because " + x + "*" + x/j + "=" + x);
                    break;
                }else{
                    message(x + " is a Prime Number");
                    break;
                }
            } 
        }
    }
    static void message(String myText){
        System.out.println(myText);
    } 

Same output:

public static void main(String[]args){
        get(10);   
    }
    static void get(int n){
        for (int x=0; x<=n; x++){
                if (x%2==0){
                    message(x +" is not a Prime number, because " + x + "*" + x/2 + "=" + x);
                    continue;
                }
                message(x + " is a Prime Number");
        }
    }
    static void message(String myText){
        System.out.println(myText);
    }   


Boolean:

public static void main(String[] args)  
    { 
         if(isPrime(11))  
         System.out.println(" true") ; 
          
         else 
         System.out.println(" false"); 
           
    } 
       // is prime or not 
       static boolean isPrime(int n) 
       { 
           // Corner case 
           if (n <= 1
               return false
          
           // Check from 2 to n-1 
           for (int i = 2; i < n; i++) 
               if (n % i == 0
                   return false
          
           return true
       }