Wednesday, 7 October 2015

JDBC ODBC Connectivity (Insert Operation)



JDBC-ODBC connectivity in JAVA(INSERT OPERATION)
To connect a database with java language program we have to follow three steps :-

1)    Creation of database and table in SQL server
2)    Creation of DSN
3)    Using this DSN in our java Program

1)    Creation of database and table in SQL server :-

Step 1 :- Click on start and find sql server management studio, it will ask for the sql server name 

Figure 1

Figure 2

Step 2 :- Click on connect.
Step 3 :-  you will get the following screen, in which we have to select the database folder for creation of our database. Now right click on it and get the another screen and select the new database option.

Figure 3

Figure 4

Step 4 :- Give the database name as in my example it is  Login_db or anything else what you want.
Step5  :- Select the Login_db folder and right click on it to create a new table.  

Figure 5
Step6  :- Specify the columns as uid and upass as shown in the above figure and save the table with the name of user1.  This is the end of part 1 of this tutorial.

2)    Creation of DSN:- for creation of DSN select the administrative tool from the control panel and the ODBC Data Source as in the following figure.

Figure 6

Now click on add and select the sql server from the list of drivers.

Figure 7

Click on finish and provide the name of DSN and Servername which is our sql server name.

Figure 8

Click on next, next, and then  specify the database name which we had just created in the above step.(Login_db)


Figure 9

Click on next and finish. This is the end of Part 2 of this tutorial and now the final step is using DSN in our java Program.

3)    Using this DSN in our java Program with the name of DB_Sample3.java

Program to insert new record in the database table:-
import java.sql.*;
class DB_Sample3
{
 public static void main(String[] args)
  {
   String i1,i2;
   try
  {
   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   Connection con=DriverManager.getConnection("jdbc:odbc:Login_DSN");
Statement st=con.createStatement();
st.executeUpdate("insert into user1 values('rakhee','12121')");
st.executeUpdate("insert into user1 values('fsf','fsf')");
con.commit();
ResultSet rs=st.executeQuery("select * from user1");
while(rs.next())
{
     i1=rs.getString(1);
     i2=rs.getString(2);
     System.out.println("id:="+i1+ " Password :-"+i2);
} }
catch(Exception e) { }
}}
Now compile the above program with javac and execute it with java
Javac DB_Sample3.java
Java DB_Sample3
When we open our table in the sql server, we can find the above records are added  in the table.

No comments:

Post a Comment