Sunday, November 22, 2009
Saturday, October 31, 2009
පමා වැඩී මම...
දුක් විදින හද..
Monday, October 26, 2009
Java Database tutorial
In this ill tl u how to connect to Java database, retrieve data, save data, update data and finally delete data in the database.... please refer to the attachments it contains source codes and the database... plz plz read the commented text in the source codes :)
here is the code for sample database+ netbeans source codes..
first you have to make a ODBC connectivity. To do that go to Control panel (if you like change it t classic mode it will make your work easy )> administrative tools> Data Sources (ODBC) then select System DSN from the opened window the select "add" and select "Driver do Microsoft Access(*.mdb)" DON'T SELECT "Microsoft Access driver (*.mdb)"... then give data source name (for example lets say it is "MyDB1"(Ill use this name in my examples)) then click on select and browse to the database you created... after selecting you should be able to see da database path just above the select button. Now your database is ready.
SQL commands
============
a SELECT statement to retrieve data
an INSERT statement to add data
a DELETE statement to remove data
an UPDATE statement to update existing data
Connecting to the database
==========================
import java.sql.*;
import javax.swing.*;
public class database1 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
con.close();
JOptionPane.showMessageDialog(null, "successfully connected");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error Connecting...");
System.out.println("Error: " + e);
}
}
}
if this runs without a error we can say that you have successfully connected the ODBC drivers and java program. :) but if you get "Error connecting.." :( then there's something wrong check your database and check whether you have configured the OBDC data source correct.
Save data to the database
=========================
to do this your database should contains a table and columns lets say table name is table1 and thr r 2 columns called column1 and column2. Please first try connecting to database before doing this.
here is the save code...
import java.sql.*;
import javax.swing.*;
public class database2 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO table1 VALUES ('value 1' , 'value 2')");
/*In the save code here it says save (INSERT) INTO table1 and save values of columns are value1 1 and value 2
note : values are inside single quotes('') and they are separated by a comma(,) also these are written inside a bracket.
this is aplicable for all the database connectivity codes
you can only save values only to the no of columns existing for example if you wont to save three values thr should be
three columns in the table otherwise it will throw a exception.
if you wont previously stored string values to be saved the statement will be look like this
String s1 = "value 1";
this string may be a retrieved value from the JTextField(lets say its object is jt1) then it should be like
String s1 = jt1.getText();
String s2 = "value 2";stmt.executeUpdate("INSERT INTO table1 VALUES ('" + s1 + "', ' " + s2 + "')");
*/
con.commit();
stmt.close();
con.close();
JOptionPane.showMessageDialog(null, "Successfully Saved");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error saving data..");
e.printStackTrace();
System.out.println("Error: " + e);
}
}
}
if you get the message saying "successfully saved" it means these values are successfully saved into the database. go to the database and open the table and you will see value 1 and value 2 is successfully saved in the database. If you get "Error saving data" you have a problem check whether you have passed values correctly, if your database is still open close it and try again.
Search data / retrieve data from the database
============================================
after saving data if you wont that data back then you can use this SELECT mechanism to retrieve those data. here is the code for that,
import java.sql.*;
import javax.swing.*;
public class database3 {
static String s1;
static String s2;
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1");// change this to whatever your DSN name is
Statement stmt = con.createStatement();
/* here it says get (SELECT) all (*) data from table1 which means this will retrieve all the available data from the database. then we are saving those data in a resultset object which is a kind of a virtual table.remember when we wont something from the database it is "stmt.executeQuery". also if you just wont to retrieve a specific row in the database it's like this.
ResultSet rs = stmt.executeQuery("SELECT * FROM table1 WHERE column1='value1'");
or
ResultSet rs = stmt.executeQuery("SELECT * FROM table1 WHERE column1='"+jt1.getText()+"'");
*/
ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
/*then in that ResultSet class it has a method next() which will check whether data is available it actually returns a boolean value. when ResultSet select all the data from the table and when after finishing selecting data next() method retrieves a boolean false which will cause to stop the loop.*/
while (rs.next()) {
s1 = rs.getString("column1");
s2 = rs.getString("column2");
System.out.println(s1 + " " + s2);
}
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error retrieving data");
}
}
}
After running this code you will be able to see it will print all the values in the database but if you got the message "Error retrieving data " then there's something wrong check if there's values in the database.
Update data in the database
===========================
this will update the existing data in the table. Its like editing data and saving.
import java.sql.*;
import javax.swing.*;
public class database4 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
Statement stmt = con.createStatement();
stmt.executeUpdate("UPDATE table1 SET column1='value3', column2='value4' WHERE column1='value1'");
/*in the update code here it says edit (UPDATE) table1 and SET values of columns to value3 and value 4 WHERE current row value is value1. Which means first search for the column1 which contains value1 and replace (update) that row with value3 and value4.
if you wont to update from a stored string values or string may be a retrieved value from the JTextField(lets say its object is jt1) then the statement will be look like this
String s1 = "value 1";
String s1 = jt1.getText();
stmt.executeUpdate(UPDATE table1 SET column1='value3', column2='value4' WHERE column1 = '" + s1 + "'");
*/
con.commit();
stmt.close();
con.close();
JOptionPane.showMessageDialog(null, "Successfully Updated");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error updating data..");
e.printStackTrace();
System.out.println("Error: " + e);
}
}
}
if you get "Successfully Updated" message you are success in updating data check database to verify :) if the message is "Error updating date.." check your database and check if theres any row containing values u are searching.
Delete data
===========
this code will delete a row of data in the database.careful when using this it remove data from the database permanantly and this has some similarities to the update code. but remember in the update code we wrote stmt.executeUpadate but here it is stmt.execute
import java.sql.*;
import javax.swing.*;
public class database5 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
Statement stmt = con.createStatement();
stmt.execute("DELETE * FROM table1 WHERE column1='value1'");
/*here it says delete (DELETE) all (*) data in the row FROM table1 WHERE column name is "column1" and value of the column1 is value1
if you wont previously stored string values to be deleted, the statement will be look like this
String s1 = "x";
if value is retrieved from the JTextField(lets say its object is jt1) then it should be like
String s1 = jt1.getText();
stmt.execute("DELETE * FROM table1 WHERE column1='"+s1+"'");
*/
con.commit();
stmt.close();
con.close();
JOptionPane.showMessageDialog(null, "Successfully deleted");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error deleting data..");
e.printStackTrace();
System.out.println("Error: " + e);
}
}
}
if you have any questions post them here or email me plz copy the error when posting...
enjoy :))))))))))
here is the code for sample database+ netbeans source codes..
http://www.4shared.com/file/207963494/54e86a12/Databasesources.html
first you have to make a ODBC connectivity. To do that go to Control panel (if you like change it t classic mode it will make your work easy )> administrative tools> Data Sources (ODBC) then select System DSN from the opened window the select "add" and select "Driver do Microsoft Access(*.mdb)" DON'T SELECT "Microsoft Access driver (*.mdb)"... then give data source name (for example lets say it is "MyDB1"(Ill use this name in my examples)) then click on select and browse to the database you created... after selecting you should be able to see da database path just above the select button. Now your database is ready.
SQL commands
============
a SELECT statement to retrieve data
an INSERT statement to add data
a DELETE statement to remove data
an UPDATE statement to update existing data
Connecting to the database
==========================
import java.sql.*;
import javax.swing.*;
public class database1 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
con.close();
JOptionPane.showMessageDialog(null, "successfully connected");
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error Connecting...");
System.out.println("Error: " + e);
}
}
}
if this runs without a error we can say that you have successfully connected the ODBC drivers and java program. :) but if you get "Error connecting.." :( then there's something wrong check your database and check whether you have configured the OBDC data source correct.
Save data to the database
=========================
to do this your database should contains a table and columns lets say table name is table1 and thr r 2 columns called column1 and column2. Please first try connecting to database before doing this.
here is the save code...
import java.sql.*;
import javax.swing.*;
public class database2 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO table1 VALUES ('value 1' , 'value 2')");
/*In the save code here it says save (INSERT) INTO table1 and save values of columns are value1 1 and value 2
note : values are inside single quotes('') and they are separated by a comma(,) also these are written inside a bracket.
this is aplicable for all the database connectivity codes
you can only save values only to the no of columns existing for example if you wont to save three values thr should be
three columns in the table otherwise it will throw a exception.
if you wont previously stored string values to be saved the statement will be look like this
String s1 = "value 1";
this string may be a retrieved value from the JTextField(lets say its object is jt1) then it should be like
String s1 = jt1.getText();
String s2 = "value 2";stmt.executeUpdate("INSERT INTO table1 VALUES ('" + s1 + "', ' " + s2 + "')");
*/
con.commit();
stmt.close();
con.close();
JOptionPane.showMessageDialog(null, "Successfully Saved");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error saving data..");
e.printStackTrace();
System.out.println("Error: " + e);
}
}
}
if you get the message saying "successfully saved" it means these values are successfully saved into the database. go to the database and open the table and you will see value 1 and value 2 is successfully saved in the database. If you get "Error saving data" you have a problem check whether you have passed values correctly, if your database is still open close it and try again.
Search data / retrieve data from the database
============================================
after saving data if you wont that data back then you can use this SELECT mechanism to retrieve those data. here is the code for that,
import java.sql.*;
import javax.swing.*;
public class database3 {
static String s1;
static String s2;
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1");// change this to whatever your DSN name is
Statement stmt = con.createStatement();
/* here it says get (SELECT) all (*) data from table1 which means this will retrieve all the available data from the database. then we are saving those data in a resultset object which is a kind of a virtual table.remember when we wont something from the database it is "stmt.executeQuery". also if you just wont to retrieve a specific row in the database it's like this.
ResultSet rs = stmt.executeQuery("SELECT * FROM table1 WHERE column1='value1'");
or
ResultSet rs = stmt.executeQuery("SELECT * FROM table1 WHERE column1='"+jt1.getText()+"'");
*/
ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
/*then in that ResultSet class it has a method next() which will check whether data is available it actually returns a boolean value. when ResultSet select all the data from the table and when after finishing selecting data next() method retrieves a boolean false which will cause to stop the loop.*/
while (rs.next()) {
s1 = rs.getString("column1");
s2 = rs.getString("column2");
System.out.println(s1 + " " + s2);
}
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error retrieving data");
}
}
}
After running this code you will be able to see it will print all the values in the database but if you got the message "Error retrieving data " then there's something wrong check if there's values in the database.
Update data in the database
===========================
this will update the existing data in the table. Its like editing data and saving.
import java.sql.*;
import javax.swing.*;
public class database4 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
Statement stmt = con.createStatement();
stmt.executeUpdate("UPDATE table1 SET column1='value3', column2='value4' WHERE column1='value1'");
/*in the update code here it says edit (UPDATE) table1 and SET values of columns to value3 and value 4 WHERE current row value is value1. Which means first search for the column1 which contains value1 and replace (update) that row with value3 and value4.
if you wont to update from a stored string values or string may be a retrieved value from the JTextField(lets say its object is jt1) then the statement will be look like this
String s1 = "value 1";
String s1 = jt1.getText();
stmt.executeUpdate(UPDATE table1 SET column1='value3', column2='value4' WHERE column1 = '" + s1 + "'");
*/
con.commit();
stmt.close();
con.close();
JOptionPane.showMessageDialog(null, "Successfully Updated");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error updating data..");
e.printStackTrace();
System.out.println("Error: " + e);
}
}
}
if you get "Successfully Updated" message you are success in updating data check database to verify :) if the message is "Error updating date.." check your database and check if theres any row containing values u are searching.
Delete data
===========
this code will delete a row of data in the database.careful when using this it remove data from the database permanantly and this has some similarities to the update code. but remember in the update code we wrote stmt.executeUpadate but here it is stmt.execute
import java.sql.*;
import javax.swing.*;
public class database5 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MyDB1"); // change this to whatever your DSN name is
Statement stmt = con.createStatement();
stmt.execute("DELETE * FROM table1 WHERE column1='value1'");
/*here it says delete (DELETE) all (*) data in the row FROM table1 WHERE column name is "column1" and value of the column1 is value1
if you wont previously stored string values to be deleted, the statement will be look like this
String s1 = "x";
if value is retrieved from the JTextField(lets say its object is jt1) then it should be like
String s1 = jt1.getText();
stmt.execute("DELETE * FROM table1 WHERE column1='"+s1+"'");
*/
con.commit();
stmt.close();
con.close();
JOptionPane.showMessageDialog(null, "Successfully deleted");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error deleting data..");
e.printStackTrace();
System.out.println("Error: " + e);
}
}
}
if you have any questions post them here or email me plz copy the error when posting...
enjoy :))))))))))
Subscribe to:
Posts (Atom)