/*
* Class CreateBaseConnection provide connect to base MySQL
*
*/
package initmaxBaseConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author initmax
*/
public class CreateBaseConnection {
private Connection CurrentConnect;
//this line need out to txt file
private String url = "jdbc:mysql://localhost:3030/maxim" +
"?autoReconnect=true&useUnicode=true&characterEncoding=utf8";
private String name = "root";
private String password = "123";
//***********************************************************************
//first need download driver, for work MySQL connect
public void DownloadDriver()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loading success!");
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
//***********************************************************************
//Connected to MySQL Base use download driver
public void Connected()
{
try
{
CurrentConnect = DriverManager.getConnection(url, name, password);
System.out.println("Connected.");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
//*********************************************************************
//disconnected base after finish work, get object connect
public int DisConnected()
{
try
{
CurrentConnect.close();
System.out.println("Disconnected.");
}
catch (SQLException e)
{
e.printStackTrace();
}
return 0;
}
public Connection GetConnection()
{
return this.CurrentConnect;
}
}
JDBC + WEB
вот класс осуществляющий взаимодействие с БД загрузку API драйвара, покдлючение, отключение..
Код:
Затем класс который в перспективе будет содержать MySQL запросы по БД
Код:
package initmaxMysqlQuery;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Statement;
/**
*
* @author initmax
*/
public class BaseQueryMysql {
private Connection CurrentConnect;
//constructor initial Current database connection
public BaseQueryMysql(Connection CurrentConnectBase)
{
CurrentConnect = CurrentConnectBase;
}
public void selectedAll()
{
try
{
Statement st = CurrentConnect.createStatement();
String query = "select * from students";
ResultSet rs = st.executeQuery(query);
String FIO;
int id_group;
while (rs.next())
{
FIO = rs.getString("FIO");
id_group = rs.getInt("id_group");
System.out.println("******************************");
System.out.println("FIO: " + FIO);
System.out.println("GROUP: " + id_group);
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Statement;
/**
*
* @author initmax
*/
public class BaseQueryMysql {
private Connection CurrentConnect;
//constructor initial Current database connection
public BaseQueryMysql(Connection CurrentConnectBase)
{
CurrentConnect = CurrentConnectBase;
}
public void selectedAll()
{
try
{
Statement st = CurrentConnect.createStatement();
String query = "select * from students";
ResultSet rs = st.executeQuery(query);
String FIO;
int id_group;
while (rs.next())
{
FIO = rs.getString("FIO");
id_group = rs.getInt("id_group");
System.out.println("******************************");
System.out.println("FIO: " + FIO);
System.out.println("GROUP: " + id_group);
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Ну и наконец класс Майн в котором буду порождать экземпляры вышеперечисленных классов и вызывать их методы
Код:
import initmaxBaseConnection.CreateBaseConnection;
import initmaxMysqlQuery.BaseQueryMysql;
import java.sql.Connection;
import java.io.*;
/**
*
* @author initmax
*/
public class ClassMain {
public static void main(String[] args)
{
//connected to MySql base
CreateBaseConnection BaseObj = new CreateBaseConnection();
BaseObj.DownloadDriver();
BaseObj.Connected();
//set current connect to database, for execute query
BaseQueryMysql QueryObj = new BaseQueryMysql(BaseObj.GetConnection());
//exec query
QueryObj.selectedAll();
//disconnect database, finish work
BaseObj.DisConnected();
}
}
import initmaxMysqlQuery.BaseQueryMysql;
import java.sql.Connection;
import java.io.*;
/**
*
* @author initmax
*/
public class ClassMain {
public static void main(String[] args)
{
//connected to MySql base
CreateBaseConnection BaseObj = new CreateBaseConnection();
BaseObj.DownloadDriver();
BaseObj.Connected();
//set current connect to database, for execute query
BaseQueryMysql QueryObj = new BaseQueryMysql(BaseObj.GetConnection());
//exec query
QueryObj.selectedAll();
//disconnect database, finish work
BaseObj.DisConnected();
}
}
В майне создаю Объект для работы с БД вызываю из него метод для загрузки драйвера для работы MySQL после чего подключаюсь к БД, затем текущее подключение BaseObj.GetConnection() передаю объекту отвечающему за запросы по БД и начинаю выводить из БД информацию.
Не накрутил ли я лишнего? если кто-то это делает более логично или просто :sample
и главный вопрос как теперь сие организовать через браузер? в сервлет Main вписать?
или как это делается?
Благодарю за внимание.
[/code]
или как это делается?[/QUOTE]
Поместить в аплет, вот как.
OutputApplet.java
Код:
/**
* This is a demonstration JDBC applet.
* It displays some simple standard output from the Coffee database.
*/
import java.applet.Applet;
import java.awt.Graphics;
import java.util.Vector;
import java.sql.*;
public class OutputApplet extends Applet implements Runnable {
private Thread worker;
private Vector queryResults;
private String message = "Initializing";
public synchronized void start() {
// Every time "start" is called we create a worker thread to
// re-evaluate the database query.
if (worker == null) {
message = "Connecting to database";
worker = new Thread(this);
worker.start();
}
}
/**
* The "run" method is called from the worker thread. Notice that
* because this method is doing potentially slow databases accesses
* we avoid making it a synchronized method.
*/
public void run() {
String url = "jdbc:mySubprotocol:myDataSource";
String query = "select COF_NAME, PRICE from COFFEES";
try {
Class.forName("myDriver.ClassName");
} catch(Exception ex) {
setError("Can't find Database driver class: " + ex);
return;
}
try {
Vector results = new Vector();
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME");
float f = rs.getFloat("PRICE");
String text = s + " " + f;
results.addElement(text);
}
stmt.close();
con.close();
setResults(results);
} catch(SQLException ex) {
setError("SQLException: " + ex);
}
}
/**
* The "paint" method is called by AWT when it wants us to
* display our current state on the screen.
*/
public synchronized void paint(Graphics g) {
// If there are no results available, display the current message.
if (queryResults == null) {
g.drawString(message, 5, 50);
return;
}
// Display the results.
g.drawString("Prices of coffee per pound: ", 5, 10);
int y = 30;
java.util.Enumeration enum = queryResults.elements();
while (enum.hasMoreElements()) {
String text = (String)enum.nextElement();
g.drawString(text, 5, y);
y = y + 15;
}
}
/**
* This private method is used to record an error message for
* later display.
*/
private synchronized void setError(String mess) {
queryResults = null;
message = mess;
worker = null;
// And ask AWT to repaint this applet.
repaint();
}
/**
* This private method is used to record the results of a query, for
* later display.
*/
private synchronized void setResults(Vector results) {
queryResults = results;
worker = null;
// And ask AWT to repaint this applet.
repaint();
}
}
* This is a demonstration JDBC applet.
* It displays some simple standard output from the Coffee database.
*/
import java.applet.Applet;
import java.awt.Graphics;
import java.util.Vector;
import java.sql.*;
public class OutputApplet extends Applet implements Runnable {
private Thread worker;
private Vector queryResults;
private String message = "Initializing";
public synchronized void start() {
// Every time "start" is called we create a worker thread to
// re-evaluate the database query.
if (worker == null) {
message = "Connecting to database";
worker = new Thread(this);
worker.start();
}
}
/**
* The "run" method is called from the worker thread. Notice that
* because this method is doing potentially slow databases accesses
* we avoid making it a synchronized method.
*/
public void run() {
String url = "jdbc:mySubprotocol:myDataSource";
String query = "select COF_NAME, PRICE from COFFEES";
try {
Class.forName("myDriver.ClassName");
} catch(Exception ex) {
setError("Can't find Database driver class: " + ex);
return;
}
try {
Vector results = new Vector();
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME");
float f = rs.getFloat("PRICE");
String text = s + " " + f;
results.addElement(text);
}
stmt.close();
con.close();
setResults(results);
} catch(SQLException ex) {
setError("SQLException: " + ex);
}
}
/**
* The "paint" method is called by AWT when it wants us to
* display our current state on the screen.
*/
public synchronized void paint(Graphics g) {
// If there are no results available, display the current message.
if (queryResults == null) {
g.drawString(message, 5, 50);
return;
}
// Display the results.
g.drawString("Prices of coffee per pound: ", 5, 10);
int y = 30;
java.util.Enumeration enum = queryResults.elements();
while (enum.hasMoreElements()) {
String text = (String)enum.nextElement();
g.drawString(text, 5, y);
y = y + 15;
}
}
/**
* This private method is used to record an error message for
* later display.
*/
private synchronized void setError(String mess) {
queryResults = null;
message = mess;
worker = null;
// And ask AWT to repaint this applet.
repaint();
}
/**
* This private method is used to record the results of a query, for
* later display.
*/
private synchronized void setResults(Vector results) {
queryResults = results;
worker = null;
// And ask AWT to repaint this applet.
repaint();
}
}
Coffeeeees.java ->
Код:
import java.sql.*;
public class CreateCoffees {
public static void main(String args[]) {
String url = "jdbc:mySubprotocol:myDataSource";
Connection con;
String createString;
createString = "create table COFFEES " +
"(COF_NAME VARCHAR(32), " +
"SUP_ID INTEGER, " +
"PRICE FLOAT, " +
"SALES INTEGER, " +
"TOTAL INTEGER)";
Statement stmt;
try {
Class.forName("myDriver.ClassName");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "myLogin", "myPassword");
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
public class CreateCoffees {
public static void main(String args[]) {
String url = "jdbc:mySubprotocol:myDataSource";
Connection con;
String createString;
createString = "create table COFFEES " +
"(COF_NAME VARCHAR(32), " +
"SUP_ID INTEGER, " +
"PRICE FLOAT, " +
"SALES INTEGER, " +
"TOTAL INTEGER)";
Statement stmt;
try {
Class.forName("myDriver.ClassName");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "myLogin", "myPassword");
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}
OutputApplet.html ->
Код:
<HTML>
<HEAD>
<TITLE> Query Output </TITLE>
</HEAD>
<BODY>
Output from query
select NAME, PRICE from COFFEES
<APPLET CODE="OutputApplet.class" WIDTH=250 HEIGHT=200>
</APPLET>
</BODY>
</HTML>
<HEAD>
<TITLE> Query Output </TITLE>
</HEAD>
<BODY>
Output from query
select NAME, PRICE from COFFEES
<APPLET CODE="OutputApplet.class" WIDTH=250 HEIGHT=200>
</APPLET>
</BODY>
</HTML>
Не оч. советую юзать апплеты. Советую посмотреть в сторону Servlets / JSP / J2EE.
Цитата: Zorkus
Не оч. советую юзать апплеты. Советую посмотреть в сторону Servlets / JSP / J2EE.
Для тестирования классов можно и поюзать апплеты. Для рабочего приложения, естественно не стоит их даже и затрагивать. Просто так кода меньше да и проверить можно быстрее. Ну хотя, кому как :)
Если же мы говорим о сервлетах, то в бой вступают сервлет-контейнеры..А там недалеко и до полноценных серверов приложений.
А там все это реализуется по другому, чем в станд-элон приложениях, не тебе это рассказывать ;)
Кстати, для упрощения работы с бд и чтобы не писать свои велосипеды, можно взглянуть на http://commons.apache.org/dbutils/.
А так же - на ORM подход :)