Sunday, September 27, 2009

JDBC

JDBC :
Use the library class java.sql.*;


import java.sql.*;

start by initializing Connection and Statement and the query string:

Connection con = null;Statement s = null;

String a = "create table Animals(name varchar(20), Type varchar(20), Age Integer)";

In order to connect to the database use a try block. Incase you were unable to connectt o the database an sql exception will give you a clearer idea about the error.

connect using the driver manager:con = DriverManager.getConnection("jdbc:mysql://zenit.senecac.on.ca:3306/username", "username", "password");

s= con.createStatement();

Execute query string:s.execute(a)--> executes the query string and creates a table in the database

At the very end close the connection:
con.close();

Inserting data into the table:
initialize the connection and statement create a try block and use the executeUpdate method.
When writing mysql syntax varchar types should be in single quotes while integers can be written as is
s.executeUpdate("insert into Animals (Name, Type, Age) values('L','" + animal + "', " + age + ")");


s.executeUpdate("insert into Animals " + "values('P','cat',6)");
If you want to delete your table you can use the following statement:s.executeUpdate("delete from Animals");


To display all of the data in the table use the ResultSet by setting it to a select query.Go through the result set in a while loop , the while loop will stop when no rows are found
while ( rs.next())

{}

The paths I used to make my application run:


PATH:C:\Sun\SDK\bin;C:\Program Files\Java\jdk1.6.0_14\bin

CLASSPATH:.;C:\Program Files\Java\jre1.6.\lib\ext\QTJava.zip;C:\Users\Owner\Desktop\mysql-connector-java-3.1.8-bin.jar;C:\Sun\SDK\lib\javaee.jar

JavaEE_HOME:C:\SUN\SDK