Steps for connecting and accessing Databases using Java-For Beginners
1> Establishing Connection
1> Load drivers
class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
2> Make Connection
Connection con=DriverManager.getConnection("dataSourceName","userName","password");
3> Creating JDBC statement
Statement stmt=con.createStatement();
4> For creation, Updation, Insertion, Deletion
stmt.executeUpdate(string query);
5> For Retieving values from the database
ResultSet rs=stmt.executeQuery(String query);
while(rs.next())
{
String str=rs.getString(fieldName);
Float fl=rs.getFloat(fieldName);
}
6> Closing the Connection
stmt.close();
con.close();
Note:-
1> before this database needs to be created.
2> data source name also needs to be created
http://support.microsoft.com/kb/305599
(for creating data source name.)
Thursday, July 31, 2008
Java Database codes-for beginners
Posted by craxfun at 11:40 AM 9 comments
Tuesday, July 29, 2008
Simplest UDP Program in Java for Beginners
The simplest program to show the data transfer among the client and server using Universal Datagram Protocol can be written as...
myServer.java
import java.io.*;
import java.net.*;
class myServer
{
public static void main(String []arg)throws IOException
{
int serverPort=5239;
int clientPort=5240;
int bufferSize=1024;
String data="Hello Client";
byte buffer[]= new buffer[buffersize];
DatagramSocket ds;
DatagramPacket dp;
buffer=data.getBytes();
ds=new DatagramSocket(serverPort);
dp=new DatagramPacket(buffer,buffer.length,InetAddress.getLocalHost(),clientPort);
ds.send(dp);
ds.close();
}
myClient.java
import java.io.*;
import java.net.*;
class myClient
{
public static void main(String []arg)throws IOException
{
int serverPort=5239;
int clientPort=5240;
int bufferSize=1024;
byte buffer[]= new buffer[buffersize];
DatagramSocket ds;
DatagramPacket dp;
ds=new DatagramSocket(clientPort);
dp=new DatagramPacket(buffer,buffer.length);
ds.recieve(dp);
System.out.println(new String(dp.getData()));
ds.close();
}
}
Explanation
We can see that there are two classes used.
DatagramSocket
DatagramPacket
DatagramSocket is used to open a socket and send or recieve packets, the reciever's port number is passed as the parameter.
DatagramPacket class has two constructors.
one for sending packets constructed as
new DatagramPacket(byte []buffer,bufferSize,Address,recieverPort)
second one is for recieving packets which is constructed as
new DatagramPacket(byte []buffer,bufferLength)
Note:- It is very important to close what you open, so always have an habit of closing every thing you open
Posted by craxfun at 1:22 PM 13 comments