// Run using:
// java -classpath .:/usr/share/java/mysql-connector-java-5.1.28.jar Example
import java.io.*;
import java.sql.*;
public class Example {
Connection cn;
// currentResults holds current results from a search() so that other methods can access them
ResultSet currentResults;
// currentItem holds the row number of an itme the user is looking at (so we can use currentResults.absolute(currentItem) to go to it
Integer currentItem;
public Example(String dbname, String userid, String password) {
cn = null;
currentResults = null;
currentItem = null;
try
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbname, userid, password);
}
catch (Exception e)
{
System.out.println("connection failed: " + e);
}
// Show all databases
// try
// {
// System.out.println("show databases");
// Statement st1 = cn.createStatement();
// ResultSet rs1 = st1.executeQuery("show databases");
// while (rs1.next())
// {
// System.out.println("Database: "+rs1.getString(1));
// }
// st1.close();
// }
// catch (SQLException e) {
// System.out.println("Query failed: " + e);
// }
// Try to use a DB
try
{
System.out.println("use " + dbname);
Statement st2 = cn.createStatement();
st2.executeUpdate("use " + dbname);
}
catch (SQLException e) {
System.out.println("Update failed: " + e);
}
//Create table test
// try
// {
// System.out.println("create table test (a int, b char(5))");
// Statement st3 = cn.createStatement();
// st3.executeUpdate("create table test (a int, b char(5))");
// }
// catch (SQLException e) {
// System.out.println("Update failed: " + e);
// System.out.println("Note from TA: Make sure your real programs can elegantly handle cases like this\n");
// }
// Show all tables.
// try
// {
// System.out.println("show tables");
// Statement st4 = cn.createStatement();
// ResultSet rs4 = st4.executeQuery("show tables");
// while (rs4.next())
// {
// System.out.println("Table: "+rs4.getString(1));
// }
// st4.close();
// }
// catch (SQLException e) {
// System.out.println("Query failed: " + e);
// }
// cn.close();
//try to show all rows in items
try
{
System.out.println("select * from items;");
Statement st4 = cn.createStatement();
ResultSet rs4 = st4.executeQuery("select * from items;");
while (rs4.next())
{ System.out.println("The current item = ",currentItem)
System.out.println("item: "+rs4.getString());
}
st4.close();
}
catch (SQLException e) {
System.out.println("Query failed: " + e);
}
cn.close();
}
catch (SQLException e)
{
System.out.println("Some other error: " + e);
}
}
public static void main (String[] args) {
String dbname = "DB_project";
String userid = "salehmak";
String password = "702449815";
Example app = new Example(dbname, userid, password);
}
}