Palindrome program in Python

In this post we shall learn how to find whether given number is a palindrome or not using python language.We have already seen palindrome program in C,C++,Java.By definition a number is called as palindrome if the reverse of the number is same as the original.

To find the reverse of the number we need to use ‘/’ and ‘%’ operators.The result of the ‘/’ is the quotient of the division and result of ‘%’ is the remainder of the division.But which number should be used to divide the given number.We use 10 for the division operation.The vital part of the code is:

while(temp>0)
	remainder = temp % 10
	temp = temp / 10
	reverse = reverse *10 + remainder

Explanation:Consider that the given number is 142.Now that number is copied to temp variable.While loop checks the temp variable.If the value is greater than 0 then it can enter the loop.
In the loop, the remainder of the % operation is stored in remainder.i.e 142% 10 gives 2 as remainder.The ‘/’ operator gives the quotient of division and it is stored in temp.i.e 142/10 gives 14 and stores it in temp variable.
Before to the loop the reverse variable is initialized to the 0.Now that 0*10+2 = 2 is stored in reverse variable.In this way loop is iterated till the condition is failed.

n = input("\nEnter any number to check for palindrome:")
temp = n
remainder = reverse = 0
while (temp > 0) :
	remainder = temp % 10
	temp = temp / 10
	reverse = reverse *10 + remainder
if(int(n) == reverse) :
	print "\n\t\tGiven number " +str(n)+" is palindrome"
else :
	print "\n\t\tGiven number " +str(n)+" is not a palindrome"

Output:
palindrome

Download the source code

Advertisements
Posted in Python | Tagged , , , , , , , | Leave a comment

Sum of digits of a number in Python

This gone be our second program in Python.We shall learn to write program to print the sum of digits of a given number.We have already seen the same program in C,C++,Java.Today we shall do the same in python.

We all know the main concept involved in finding sum of digits.First we need to separate each digit from the given number.And then we need to add them all to calculate the sum of digits.To separate a digit from the given number we use the modulus operator (%).Because if any number is divide by 10 we get the last digit of the number as remainder.So that we can get all the digits present in the number.Now we shall write the code and test it.

n = input("\nEnter any number to find the sum of digits of it:")  #To get the input from the user.
temp = n = int(n) #String to int
remainder = sum = 0 #Initialization of remainder and sum.
while (  temp > 0) :
	remainder = temp % 10
	temp = temp/10
	sum = sum +remainder
print ("\nSum of digits of  %d %d" % (n,sum))

The default datatype for a variable assigned by input statement is String.Since we are going to use that number in while we need to typecast it to int.
Output:
sum of digits

Download the source code

Posted in Python | Tagged , , , , , , , , , , , , | Leave a comment

Loops in Python

Loops are we much useful to do a repeated set of work.For example, consider printing 1 to 10. In order to print without using loops we need to write the print statement 10 times.If we need to print 100 numbers,then it can be some irksome task.With the help of loops we use print any number of numbers by writing a single print statement.

Every Programming language contains For,While and do..while loops.But python do not support do..while loop but we can implement it in different way.In this tutorial we are going to teach you the basic syntax for using for and while loops.

For loop: Comparing to other loop statements for loop is more handy,because we can initialize,check the condition,increment/decrement the loop variable in a single line.Before we learn about for loop we need to learn range() function in python. range() is used to specify the limit.If range(6),then it starts from 0 to 5.If range(1,6) then it starts from 1 and ends at 5.If range(1,6,2) then the limit is 6/2=3.
The basic syntax for using for loop is:

for x in range(limit) :
   print x

Explanation:Now the x value will be initialized with 0 and it ends with n-1 value.These values will be printed using print method.
While Loop:It is also called as entry controlled loop.If the condition is true then only the statements present in it are executed.
The basic syntax of while loop is

while(condition) :
    <true statements>

Explanation:If the condition is satisfied then only the true statements in the while loop will be executed.

Posted in Python | Tagged , , , , , , , , , , , , , , , , | Leave a comment

Input and Decision Making Statements in Python

In this tutorial we shall learn about Input and Decision Making statements.To get the data from the user we need to use input statements.Input statement in python is variable_name = input(“Text_to_be_displayed”);.The input statement is a predefined function which has String has parameter to display the message to the user.Now the value entered by the user will be stored in the variable.
Let us write a simple program to demonstrate the input statement.In this program we request the user to enter his/her age and display the same age to the user.

age = input("Please enter your Age:");
print("Your entered your age as " + age); 

Output:
input_demo

Decision Making Statement: In all programming language Decision Making Statements are nothing but if statements.We all know that there are 4 type of if statements.But the syntax of if statements may vary depending upon the language. Python too have different syntax for if statements.We shall learn.
Simple if Statement:The syntax of simple if statement is

if (condition) :
        <true statements>
        <true statements>
              .
              .
              .
        <true statements>

if…else Statement: The syntax of if else is

if (condition) :
        <true statements>
        <true statements>
              .
              .
else :
       <false statements>
       <false statements>
              .
              .

Nested if…else Statements: The syntax of nested if-else statements is

if (condition 1):
      if(condition 2) :
              <true statements>
      else :
              <false statements>
else :
       if (condition 3) :
             <true statements>
       else :
             <false Statements>

else…if: With comparison to other languages in python else if have different syntax

if (condition 1 ) :
          <true statements>
elif (condition 2) :
          <true statements>
elif (condition 3) :
          <true statements>
.
.
.
elif(condition n)
         <true statements>

These are the decision making statements present in python and their respective syntax.One more thing Python doesn’t support Switch statements

Posted in Python | Tagged , , , , , , , , , , , | Leave a comment

Hello World in python

Today we are going to start learning new programming language Python.In recent time it gained popularity because of it’s simplicity and we can complete our program with in fewer lines of code.It is both interpreter and complied.

It is developed in the year 1991 by Guido van Rossum.Python is object-oriented and structured programming language supporting both types of formats.You can install python on your system by downloading the files from their site.Today we shall learn about making a simple and basic Hello world program in python langauge.

Before writing the program we need to know have basic knowledge.Python doesn’t have any main function,so we need to worry about writing a main function in the program.To print a line we use the keyword print(“”) with the text placed in between parentheses.

Now we shall write the program in which we just print the Hello world statement

print "Hello world"
print "Welcome to the world of Python"

Output:
hello_world

Posted in Python | Tagged , , , , , , , , , , , , , , , | Leave a comment

Sample Applet program in Java

Applets are the small applications programmed in Java and embedded in html code. Usually applets are delivered to user as byte-code.Every page in a website contains applet code and is executed within a JavaVirtualMachine(JVM).We can distinguish a general java program to applets easily,since applet do not have main method in them.

To create an applet we need to import java.appet.* package.This package contains definition of all the keywords of applets.We need to extend the class Applet to our class which contains the applet methods.It is just inheriting Applet class to out class.We need to make this class has public because some other class may need to use our class.

Applets contains five inbuilt methods:

  • init()
  • start()
  • paint()
  • stop()
  • destroy()

These are invoked in the order they are written above.when applet is started inti() method used for initialization of variable is invoked first.Then the methods start() is invoked.The paint method is used for displaying the text on the applet screen.
Today we shall see a sample Applet program.

import java.applet.*;
import java.awt.*;
/*
<applet code="app_demo" height=200 width=200>
</applet>
*/
public class app_demo extends Applet 
{
	public void paint(Graphics g)
		{
			g.drawString("This data is displayed on the applet screen",200,200);
		}
}

Explanation:In the above program after importing the required the package,we have written some code.This code is the html code which is directly written in the our applet program.The applet tag is used to tell the compiler that this program is an applet and it won’t contain a main method.While defining a paint method we declared an object for Graphics class which is used to invoke the drawString() method to display the text.
The drawString() method contains parameters String,int,int.The string is for the message to be displayed and the int ,int are for defining the position of the message.

To compile the applet program from cmd we use the following command:

appletviewer classname.java

Output:
app_demo

Download the source code

Posted in Java | Tagged , , , , , , , , , , , , , , , , , , , , , , | Leave a comment

Appending data to the existing data in java

In real life we may encounter a situation in which may need to write the new data in a file without loosing old data.This is called as appending of data.We can make this using many classes present in the Java io package.In this post we shall make it using FileOutputStream class which we have used to write the data to a file.

One of the constructor of the FileOutputStream is:

FileOutputStream("Name_of_the_file",boolean);

We use this constructor with true as the value for boolean. If didn’t use the boolean value it will overwrite the data present in the file.In the following program I’m appending a string to the data present in the file.

import java.io.*;
class fileappend
{
	 public static void main(String arg[]) 
	{
		try{
			FileOutputStream fos = new FileOutputStream("append.txt",true);
			String name = "\nThis is appended to the existing content....!!!";
			byte b[] = name.getBytes();
			for(int i=0;i<b.length;i++)
				fos.write(b[i]);
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}

Output:

file_append

Download the source code

Posted in Java | Tagged , , , , | Leave a comment

Copying data from one file to other file using java

Before to this post we have learnt about writing data to a File and reading data from the File.In our today’s post we shall learn about copying the data from one File to the other File.This is pretty easy and we shall use the same concepts which we have discussed till now.

To copy the data from a file,first we need to open the file in reading mode(as input).Now we shall read all the data present in the file and store it in a byte array.We need to open the destination or target file in writing mode and we shall write the data present in the byte array into the target file.

import java.io.*;
class filecopy
{
	public static void main(String arg[])
	{
		try
		{
			FileInputStream fis = new FileInputStream("source.txt");
			int size = fis.available();
			char ch[] = new char[size]; 
			String str[] = new String[size];
			for(int i=0;i<size;i++)
			{
				ch[i] = (char)fis.read();
			}
			FileOutputStream fos = new FileOutputStream("destination.txt");
			byte b[] = new byte[ch.length];
			for(int i=0;i<size;i++)
			{
				b[i] = (byte) ch[i];
				fos.write(b[i]);
			}	
			fos.close();		
		}
		catch(Exception e)
		{
			System.out.print(e);
		}
	}
}

Output:
java_filecopy_01
filecopy_source
file_copy_dest

Download the source code!

Posted in Java | Tagged , , , , , , , , | Leave a comment

Creating and Writing Excel file in Java

In our earlier post we have learned about creating and writing data to a .txt file in Java.In this tutorial we shall learn about creating and writing data to a excel file.There are two ways in creating an Excel file in Java.We can create it using File class or by using POI library methods.Today, we shall learn about creating the Excel file using File classes.

While creating a .txt file, we have first created an object to the FileOutputStream class and we have used f1.txt as the file path.To create an Excel we need to change the extension to .xls.

FileOutputStream fos = new FileOutputStream("store.xls"); 

In the above described example we are creating an Excel file as store which stores the data of a super market.To save the data in the file we need to use the sequence character \t.we use \t because the width between two columns in Excel sheet is 5 spaces or a single tab.To write the data into the next row of the spread sheet we use the sequence character \n.Now we shall write the program with above information.

import java.io.*;
class fileswritedemoxls
{
	public static void main(String arg[])
		{
			try
			{
	  			String header="Item\tQuantity(kg)\tPrice";
				byte b[] = header.getBytes();
				FileOutputStream fos = new FileOutputStream("store.xls");
				for(int i=0;i<header.length;i++)
				{
					fos.write(b[i]);
				}

				String row1="\nSugar\t2.5\t60";
				byte b1[] = row1.getBytes();
				for(int i=0;i<b1.length;i++)
				{
					fos.write(b1[i]);
				}

				fos.close();
			}
			catch(Exception e)
			{
				System.out.print(e);
			}
		}
}

Description:In the above program we are inserting two rows…..one as heading for the column and other row is the items present in the store.
Output:
filewritedemoxls
filewritedemoxls2

Click here to download the source code

Posted in Java | Leave a comment

Java program to write data into a file

Files are the most complicated concept in any programming language.In this tutorial we shall make it simpler by learning some basic techniques in File.There are two types of operation done on files.First, we can write the data into the file.The other operation is reading the data from the file.We shall go in detail now..

To write the data into a file we use the class FileOutputStream and the methods defined in that class.To utilize the methods defined in this class we need to create the objects for this class.There is a constructor defined for this class and the general form of this constructor is
FileOutputStream(String filepath);
For creating an object we use the following syntax.

FileOutputStream fis = new FileOutputStream("name_of_the_file");

With this we have created the objects for the class,now we need to invoke the suitable method defined in the class for writing the data.For this we use the method write() with the data to be wrote has a parameter.The main step in using the FileOutputStream is,whenever we are writing the data we need to convert the data into bytes.

import java.io.*;
class fileswritedemo
{
	public static void main(String arg[])
		{
			try
			{
	  			String str="I Love Java Programming";
				byte b[] = str.getBytes();
				FileOutputStream fos = new FileOutputStream("fi.txt");
				for(int i=0;i<b.length;i++)
				{
					fos.write(b[i]);
				}
				fos.close();
			}
			catch(Exception e)
			{
				System.out.print(e);
			}
		}
}

Output:
fileswritedemo

fileswritedemo2

Click here to download the program

Posted in Java | Tagged , , , , , , , | 2 Comments

How to set up a colors XML file

ProgramThat;

It is essential to have a colors XML file in every android project you create. To be used the same color multiple times and hardcode it is not good programming practise. It is easy to forget about one when you are a beginner.

I am going to step you through how to create one and link it up to your android page. To do so I am going to use the main page which we have already created in the previous guides.

1. Go to values Image

 

2. Right click on values > new > Values resource file

Image

3. A new dialog box should then show up enabling you to enter a name for the resource.  It should always be called colors.

Image

4. You will then be taken to you new XML page once you click OK. In there you can begin to declare the colors which you…

View original post 251 more words

Posted in Android Programming | Leave a comment

Prime Number Program in C

In today’s tutorial we are going to learn about writing prime number program using C.A number is said to be prime number if and only if it is divisible by 2 otherwise it is not a prime number.

The meaning of divisibility by 2 is the remainder should be 0.To find the remainder of a division we use the operator %.The operator / gives you the quotient of the division.In order to decide whether the number is prime number or not we need to check the remainder of the division of the number with 2.

Let us write the program use the % operator.In the below program we ask the limit from the user,upto which number we need to find the prime numbers.The output is the list of all prime number from 2 to the given limit.

#include<stdio.h>
#include<conio.h>
void main()
{
  int n,i,j,flag=0;
  clrscr();
  printf("\nEnter the limit to find the prime numbers:");
  scanf("%d",&n);
  for(i=2;i<n;i++)
  {
	flag=0;
	for(j=2;j<i;j++)
	{
		if(i % j == 0)
			flag++;
	}
	if(flag == 0)
	{

		printf("\nPrime number : %d",i);
	}
  }
  getch();
}

Output:
prime
Download the source code

Posted in C | Tagged , , , , | Leave a comment

Palindrome Number Program in C

A number is said to be palindrome if it satisfy’s a condition,the reverse of the number should be same as the original number.For finding the reverse of the given number we need to get the individual digits of given number as we have done in finding the sum of digits of a given number.I shall explain it again.

To get the last digit of a number, we need to divide the given number with 10 and remainder which we get as a result is the last digit of the number.If the given number is 789 and if we divide the number with 10 we get 9 as remainder and remaining two digits 78 as quotient.If we divide the number 78 by 10 then we get 8 as remainder and 7 as quotient.By dividing 7 by 10 we get 7 as remainder and 0 as quotient.So we have got all the digits of the given number.

By using the same logic in our program we are going to check for palindrome program.In the program we are using the variable n for storing the input,remainder for storing the remainder after each division of number with 10 and reverse for finding the reverse of the number.

#include<stdio.h>
#include<conio.h>
void main()
{
	int n,remainder,rev=0,temp;
	clrscr();
	printf("Enter a number to check whether palindrome or not:");
	scanf("%d",&n);
	temp = n;
	while(temp>0)
	{
		remainder = temp%10;
		temp = temp/10;
		rev=rev*10+remainder;
	}
	printf("Reverse value is :%d",rev);
	if(rev == n)
		printf("\nGiven number %d is palindrome",n);
	else
		printf("Given number %d is not palindrome",n);
	getch();
}

Output:
palindrome
Download the source code

Posted in C | Tagged , , , , , , , , | 1 Comment

Sum of digits of a Number in C

In this tutorial we are going to learn about adding digits present in a given number.The main concept of this problem is…..If the input is 225 then the output should be 9 i.e is addition 2+2+5.The logic behind it is we need to get the single digits of the number..i.e is 5,2,2 separately.

To exclude the numbers from the given digit we use the number 10.The special property of number 10 is, if a number is divided by 10 then the remainder will be the last digit of the number and quotient will be other digits present in the number.For example let the number be 225.If we divide the number by 10 then the remainder will be 5 and the quotient will be 22.Therefore we got the number 5 from the given digit.Now the program is

#include<stdio.h>
#include<conio.h>
void main()
{
	int num,remainder,sum=0;
	clrscr();
	printf("\t************Sum of digits of given number**********");
	printf("\n\nEnter any number to find the sum of digits present:");
	scanf("%d",&num);
	while(num>0)
	{
		remainder = num%10;
		num = num/10;
		sum = sum +remainder;
	}
	printf("\nSum of digits of given number is:%d",sum);
	getch();
}

Output:
sumofdigits
Download source code

Posted in C | Tagged , , , , , , | 1 Comment

Fibonacci Series program in C

Fibonacci series starts with 0 and 1.The third element of fibonacci series in obtained by adding the first,two elements of the series.If we need to find an element of the series we add the two numbers which are just behind it.We can generalize the equation as,the nth element of the series is obtained by adding n-1 and n-22,1 element of the series.

Let us see an example…..As we know the first two elements are 0 and 1.The third element of the series is obtained by adding 0 and 1,hence the third element is 0+1=1.Therefore the series would be 0,1,1…Fourth element of the series is addition of second and third element….i.e 1+1=2..hence the fourth element is 2 and series will be 0,1,1,2….

By observing the program we need to change the values of a and b repeatedly…..because we need to add two values behind to it.In the below program the input is an integer which is length of the series.

#include<stdio.h>
#include<conio.h>
void main()
{
	int a=0,b=1,c,i,n;
	clrscr();
	printf("\t\t*********Fibonnaci series************");
	printf("\nEnter number of terms need to be present in the series:");
	scanf("%d",&n);
	printf("\n%d  %d  ",a,b);
	for(i=0;i<n-2;i++)
	{
		c = a+b;
		printf("%d  ",c);
		a=b;
		b=c;
	}
	getch();
}

Output:
fib_c
Download the source code.

Posted in C | Tagged , , , , , , , , , , , , , , | Leave a comment

Switch case in C

In one of earlier post we introduced to decision making statements in c.Today we shall learn about one of the decision making statement in C “switch statement“.The switch statement allows you for checking a equality among the options available and then perform actions according to it.For checking the equality we use the keyword case.After executing the statements related to the choice we need to break it or else it will executed continuously without any break.

Syntax:

swtich(value)
	{
		case val1: statements for execution
			 break;
		case val2: statements for execution
			 break;
		.	
		.
		.
		.
		default: statements for execution
			exit();
	}

Each switch may or may not contain a default statement.If the given value doesn’t matches to any of the case value then the default statement’s execution will be done.A simple program to display the execution of switch statement and to display the name of the day with input as number.

#include<stdio.h>
#include<conio.h>
void main()
{
	int n;
	clrscr();
	printf("Enter a number in the range of 1-7 to show the corresponding day of the week:");
	scanf("%d",&n);
	switch(n)
	{
		case 1:printf("\n\tFirst day of the week is Monday");
			break;
		case 2:printf("\n\tSecond day of the week is Tuesday");
			break;
		case 3:printf("\n\tThird day of the week is Wednesday");
			break;
		case 4:printf("\n\tFourth day of the week is Thursday");
			break;
		case 5:printf("\n\tFifth day of the week is Friday");
			break;
		case 6:printf("\n\tSixth day of the week is Saturday");
			break;
                case 7:printf("\n\tSeventh day of the week is Sunday");
			break;
	}
 getch();
}

Output:
switch_demo
Download the source code

Posted in C | Tagged , , , , , , , , , | Leave a comment

Java program for Inserting rows using preparedstatement

In our earlier post we have learned about making connection from a Java program to the databases.But the drawback of just using createStatement() and excuteuery(),is that we can request for run time values and then insert it into the database.

To overcome this drawback,there is a special type of statements called as PreparedStatement for inserting the values into the database which are given through command line arguments.These statements are used to insert rows into the database with values given through command line arguments.
For creating a prepared statement,we need to create an object to the class PreparedStatement and assign the query init.After getting the values and inserting it into the query we need to update the database.For this we use the function executeUpdate();

We shall write a program to demonstrate the use of prepared statement.

import java.sql.*;
class preparedstatementDemo1
{
	public static void main(String arg[]) throws Exception
		{
			String id="";
			String pd="";
			String url="jdbc:odbc:company";
			String query="INSERT INTO players (PlayerName,PlayerAge) VALUES (? , ?)";
			ResultSet res;
			try
			{
				Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
				Connection con;
				con = DriverManager.getConnection(url,id,pd);
				Statement st = con.createStatement();
				PreparedStatement pst = con.prepareStatement(query);
				pst.setString(1,arg[0]);
				pst.setString(2,arg[1]);
				pst.executeUpdate();
				 res = st.executeQuery("select * from players");
				while(res.next())
				{
					System.out.println(res.getString(2)+"   "+res.getString(3)+"  ");
				}
			}
			catch(Exception e)
			{
				System.out.print(e);
			}	
		}
}

preparedstatementDemo1
Click here to download the source code

Posted in Java | Tagged , , , , , | Leave a comment

Connecting Java to Mysql Database

In our earlier post we learned about Connecting Java to Microsoft Access.In today’s post we shall learn about connecting Java to Mysql database.For connecting Java to Mysql we need to install Mysql odbc drivers.You can get the drivers from their original website.After downloading the drivers install them on your system.

So you have done the primary step in connecting Java to Mysql.Now open control panel,goto administrative tools.Their select DataSources(odbc).Now you get a dialog box which looks like this and select the add option init.
sql_connection_1
After selecting the add option there search for”MYSQL ODBC 5.2 ANSI Driver” and select it.It opens a dialog box to enter the details of the sql database…..
Connector_ODBC_window
In the Data source Name enter the name of the source file.For TCP/IP give it as localHost and keep the port as default.Now enter the user and password details of the Mysql database.After the details of user and password click on test.If connection is ok,then in the field Database we can see the list of the tables present in the given database and select the desired one. With this we have created a connection between java and Mysql.

Now we shall write the program which is similar to that of using Java with Microsoft Access Database.

import java.sql.*;
public class sqldemo 
{
  public static void main(String arg[]) throws Exception
    {
           String url="jdbc:mysql://localhost/emp1"; //protocol:subprotocol:sourcefile
           String id="root";     //User name of the Mysql
           String pd="abcd";    //Password of the Mysql database
           ResultSet res;
           try
	{
	 	Class.forName("com.mysql.jdbc.Driver");
 		Connection con;
		con = DriverManager.getConnection(url,id,pd);
 		Statement st = con.createStatement();
		res = st.executeQuery("select * from emp");
		while(res.next())
			{
				System.out.println(res.getString(1)+"  "+res.getString(2));
			}
	}
           catch(Exception e)
	{
		System.out.print(e);
	}
   }
}

Description:In the above program we have used the method forName() which is present in the class “Class” for dynamically load the class.Next we have declared a string url for telling the protocol,sub-protocol and data source which we are going to use.
Now we need to make connection which is done by using the method getConnection() which is present in the class DriverManager and it returns the object of the Connection class.In order to execute the statements,first we need to create a Statement.For this we are going to use the method createStatement() by using the object of Connection class and it returns an object of Statement class.For executing a query we shall use the method executeQuery() which is invoked through the object of the statement class.It returns result set of the query which is stored in an object of ResultSet class.So the output of the above program is
OUTPUT:
sql_demo
To download the program click here:download

Posted in Java | Tagged , , , , , , | Leave a comment

Connecting Java to Microsoft Access DataBase

Database plays a very important role in maintaining a web site or a organization details.It will be exciting if we are able to use the data present in Database in our program.One of the important features of Java is that we can connect to database using it.Connecting Java to Db is called as Java connectivity.With help of Java connectivity we can retrieve, update the data present in the Database.

For connecting the database to the Java program we need to install the drivers.In our tutorial we going to use Microsoft Access as the database.For installing the drivers we need jdbc-odbc files.Jdbc drivers are available with java api kit.Microsoft provides the odbc drivers to the users defaulty…but we need to install them.To install them follow these steps.
Step 1: Go to control Panel
Step 2: Select administrative tools.
Step 3: Select Data Sources(odbc).
Step 4: There select User DSN…..and click on Add
Step 5: Then select the ms access(*.mdb)
Step 6: Now give the name of the data source which you are going to use.
Step 7: Then click on select button and then find your database…..and then click on ok

With this you installed the drivers for connecting the java the to Ms Access.

Now we shall learn how to write the java code for connecting to the database.The main important steps in any one the database connecting program is:
Step 1: specify the rivers which you are going to use in the program.For this we need to invoke a method called as forName() which is present in the class “Class”.

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Step 2: Now we need to start the connection to the Database.For this we use the method getConnection() which is present in the class DriverManager.Which return an object of connection class.We need to pass the protocol,user id and password for the database.The url consists of three parts protocol,subprotocol,sourcename.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,userid,pswd);

Step 3:Now we need to create an statement to execute the queries.For this we use the method createStatement() which is present in the Connection class and we use the con object to call the method,Which returns an object of statement class.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,userid,pswd);
Statement st = con.createStatement();

Step 4:Now we shall execute the queries on the table.For this we use the method executeQuery() which is present in the class Statement and we use the object st.It returns the set of results of the operation and we need to store them in an object of ResultSet.

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con = DriverManager.getConnection(url,userid,pswd);
Statement st = con.createStatement();
Resultset res = st.executeQuery("select * from emp");

Now the entire code for the program is:

import java.sql.*;
public class msaccessdemo
{
	public static void main(String arg[])
	  {
		ResultSet res;     //To store the result of the query
		String url="jdbc:odbc:company";
		String id="";
		String pd="";
		try
		  {
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			Connection con;
			con = DriverManager.getConnection(url.id,pd);
			Statement st = con.createStatement();
			res = st.executeQuery("select * from emp");
			while(res.next())
			   {
			      System.out.print("res.getString(1)+"       "+res.getString(2));
			    }
		    }
		catch(Exception e)
		  {
			System.out.print(e);
		  }
      }
}

OUTPUT:
msaccessdemo
To download the program click here:download

Posted in Java | Tagged , , , , , , , , , , , | 2 Comments