package example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.jdbc.*
// or you will have problems!
import java.io.*;
import java.awt.*;
import java.sql.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class MySqlTwoResin extends HttpServlet {
public void init() throws ServletException
{
}
public void doGet (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Connection conn;
Integer createInitialTable = 0;
//try {
//Connection conn = DriverManager.getConnection("jdbc:mysql:
//localhost/test?user=root&password=");
//} catch (SQLException ex) {
//out.println("SQLException: " + ex.getMessage());
//out.println("SQLState: " + ex.getSQLState());
//out.println("VendorError: " + ex.getErrorCode());
//}
PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost/resin1";
try {
Class.forName ("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
out.println ("Cannot instantiate jdbc driver");
// handle the error
}
try {
conn = DriverManager.getConnection (url, userName, password);
out.println ("Database connection established");
//String query = "SELECT * FROM user";
Statement stmt = conn.createStatement ();
if (createInitialTable == 1) {
String createTableCoffees = "CREATE TABLE CHOCOLATES (CHOC_NAME VARCHAR(32), SUPPLIER_ID INTEGER, PRICE FLOAT, SALES INTEGER, TOTAL INTEGER)";
stmt.executeUpdate(createTableCoffees);
stmt.executeUpdate("INSERT INTO CHOCOLATES VALUES ('Dark', 101, 7.99, 0, 0)");
stmt.executeUpdate("INSERT INTO CHOCOLATES VALUES ('Light', 101, 7.94, 0, 0)");
}
String query = "SELECT CHOC_NAME, SUPPLIER_ID, PRICE FROM CHOCOLATES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("CHOC_NAME");
int supl = rs.getInt("SUPPLIER_ID");
float n = rs.getFloat("PRICE");
out.println(s + " " + n + " " + supl + "
");
}
//ResultSet rs = stmt.executeQuery (query);
//int numCols = rs.getMetaData().getColumnCount ();
//out.println("Retrieved " + numCols + " columns");
//while ( rs.next() ) {
// out.println("
");
// for (int i=1; i<=numCols; i++) {
// out.print(rs.getString(i) + " " );
// } // end for
// out.println("
");
//} // end while
//rs.close();
stmt.close();
conn.close();
} catch (SQLException ex) {
// handle any errors
out.println("Got error.
");
while (ex != null) {
out.println ("SQL Exception: " + ex.getMessage ());
out.println("SQLState: " + ex.getSQLState());
out.println("VendorError: " + ex.getErrorCode() + "
");
ex = ex.getNextException ();
} // end while
}
out.println("Finished.
");
}
}