i am trying to do java database connectivity in eclipse juno using eclipse but i am getting the following error comes
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
suggest me some solutions..........
this is my code :
package example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Connect {
public static Connection getConnection()
{
String url="jdbc:mysql://localhost:3306/demo";
String drive="com.mysql.jdbc.Driver";
//String databse="demo";
String user="root";
String password="abc";
Connection conn=null;
try
{
Class.forName(drive);
conn=DriverManager.getConnection(url, user, password);
}
catch (Exception e)
{
System.out.println(""+e);
}
return conn;
}
public static void main(String[] args)
{
Connection conn=null;
PreparedStatement pstmt=null;
try
{
conn=getConnection();
conn.setAutoCommit(false);
pstmt=conn.prepareStatement("insert into testlongtele(address,name)values(?,?)");
pstmt.setString(0, "NIRAV");
pstmt.setString(1, "KAMANI");
pstmt.executeUpdate();
pstmt.close();
conn.commit();
conn.close();
}
catch(Exception e)
{
System.out.println(""+e);
}
}
}
From This link:
Possible Cause of this error is:
1) You don't have mysql-connector.jar in your Classpath. as stated earlier this jar file contains "com.mysql.jdbc.Driver" class it must be present in classpath in order to successful connection to mysql database. you can downlad mysql-connector.jar from mysql.com.
2) mysql-connector.jar is in your classpath but somehow your classpath is getting overridden.
Classpath is tricky in Java and classpath specified in jar may override CLASSPATH path variable. See how classpath works in Java to understand this issue in detail.
3) mysql-connector.jar is in classpath but current user doesn't have read permission.
This problem often happens in Unix or Linux operating system which has sophisticated file and directory permission based on user, group and owner level. just get the right permission and run your program again.
You can add:
class.forName(driver).newInstance();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mindtree.kalinga.exception.ConnectionfailedException;
public class JdbcConnection {
private static JdbcConnection jdbcConnection;
private static Connection dbConnection;
private JdbcConnection() {
}
public static JdbcConnection getInstance() {
if (jdbcConnection == null)
jdbcConnection = new JdbcConnection();
return jdbcConnection;
}
public static void createConnection() throws ConnectionfailedException {
try {
dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mindtree", "root", "Welcome123");
} catch (SQLException e) {
throw new ConnectionfailedException("Error creating the connection to database", e);
}
System.out.println("Connection to db Established!");
}
public static Connection getConnection() {
return dbConnection;
}
public static void closeConnection() throws ConnectionfailedException {
try {
dbConnection.close();
} catch (SQLException e) {
throw new ConnectionfailedException("connection not closed properly", e);
}
}
}
--------------------------------------
Main
--------------------------------------
package com.mindtree.kalinga.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.exception.ConnectionfailedException;
import com.mindtree.kalinga.service.Mindtreeservice;
import com.mindtree.kalinga.serviceimp.Mindtreeserviceimp;
import com.mindtree.kalinga.utility.JdbcConnection;
public class MindtreeMain {
static Scanner in = new Scanner(System.in);
static Mindtreeservice ms = new Mindtreeserviceimp();
public static void main(String[] args) {
try {
JdbcConnection.createConnection();
} catch (ConnectionfailedException e) {
System.out.println("Not able to connect to database! Terminating application!");
e.printStackTrace();
}
MindtreeMain mm = new MindtreeMain();
int i = 1;
while (i == 1) {
System.out.println("1. to enter the detail\n" + "2. fetch the detail\n" + "3. to exit");
int key = in.nextInt();
switch (key) {
case 1:
Mindtree m = mm.createminds();
break;
case 2:
List<Mindtree> ml = new ArrayList<>();
mm.display(ml);
break;
case 3:
i = 0;
break;
default:
break;
}
}
}
private Mindtree createminds() {
// TODO Auto-generated method stub
System.out.println("enter the id of mind");
int id = in.nextInt();
in.nextLine();
System.out.println("enter the name of mind");
String name = in.nextLine();
System.out.println("ente the address of minds");
String address = in.nextLine();
Mindtree m = new Mindtree(id, name, address);
return m;
}
private void display(List<Mindtree> mind) {
for (Mindtree i : mind) {
System.out.println(i.getMid());
System.out.println(i.getName());
System.out.println(i.getAddress());
}
}
}
-------------------------------------------------
service
-------------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreeservice {
public void insertmind(Mindtree m);
public List<Mindtree> getAllminds();
}
---------------------------------------------
serviceimp
---------------------------------------------
package com.mindtree.kalinga.serviceimp;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.daoimp.Mindtreedaoimp;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.service.Mindtreeservice;
public class Mindtreeserviceimp implements Mindtreeservice {
Mindtreedao md = new Mindtreedaoimp();
#Override
public void insertmind(Mindtree m) {
// TODO Auto-generated method stub
md.insertMindToDb(m);
}
#Override
public List<Mindtree> getAllminds() {
// TODO Auto-generated method stub
return md.getAllMindFromDb();
}
}
--------------------------------------------
dao
--------------------------------------------
import java.util.List;
import com.mindtree.kalinga.entity.Mindtree;
public interface Mindtreedao {
public void insertMindToDb(Mindtree m);
public List<Mindtree> getAllMindFromDb();
}
-------------------------------------------
daoimp
-------------------------------------------
package com.mindtree.kalinga.daoimp;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.mindtree.kalinga.dao.Mindtreedao;
import com.mindtree.kalinga.entity.Mindtree;
import com.mindtree.kalinga.utility.JdbcConnection;
import com.mysql.jdbc.Statement;
public class Mindtreedaoimp implements Mindtreedao {
#Override
public void insertMindToDb(Mindtree m) {
Connection con = JdbcConnection.getConnection();
String query = "insert into mindtree values(?,?,?);";
PreparedStatement ps = null;
try {
ps = con.prepareStatement(query);
ps.setInt(1, m.getMid());
ps.setString(2, m.getName());
ps.setString(3, m.getAddress());
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
}
#Override
public List<Mindtree> getAllMindFromDb() {
// TODO Auto-generated method stub
List<Mindtree> mtl = new ArrayList<Mindtree>();
Connection con = JdbcConnection.getConnection();
String query = "select * from mindtree;";
Statement st = null;
ResultSet rs = null;
try {
st = (Statement) con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
Mindtree m = new Mindtree(rs.getInt(1), rs.getString(2), rs.getString(3));
mtl.add(m);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mtl;
}
}
-----------------------------------------------
exception
package com.mindtree.kalinga.exception;
public class ConnectionfailedException extends Exception {
public ConnectionfailedException() {
super();
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public ConnectionfailedException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
-----------------------------
entity
-----------------------------
package com.mindtree.kalinga.entity;
public class Mindtree {
int Mid;
String name;
String address;
public Mindtree(int mid, String name, String address)
{
Mid = mid;
this.name = name;
this.address = address;
}
public int getMid() {
return Mid;
}
public void setMid(int mid) {
Mid = mid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Related
I've been working at this for almost a day and a half now and I can't seem to work this error out. I don't know why the ResultSet is being closed. Maybe some of you can help me out.
MySQLDatabase:
package net.gielinor.network.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class MySQLDatabase {
private String host;
private String database;
private String username;
private String password;
private Connection connection = null;
private Statement statement;
public MySQLDatabase(String host, String database, String username, String password) {
this.host = host;
this.database = database;
this.username = username;
this.password = password;
}
public abstract void cycle() throws SQLException;
public abstract void ping();
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(String.format("jdbc:mysql://%s/%s", host, database), username, password);
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ping(String table, String variable) {
try {
statement.executeQuery(String.format("SELECT * FROM `%s` WHERE `%s` = 'null'", table, variable));
} catch (Exception e) {
connect();
}
}
public ResultSet query(String query) throws SQLException {
if (query.toLowerCase().startsWith("select")) {
return statement.executeQuery(query);
} else {
statement.executeUpdate(query);
}
return null;
}
public Connection getConnection() {
return connection;
}
}
MySQLHandler
package net.gielinor.network.sql;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import net.gielinor.network.sql.impl.MySQLDonation;
public class MySQLHandler extends Thread {
private static final MySQLHandler mysqlHandler = new MySQLHandler();
public static MySQLHandler getMySQLHandler() {
return mysqlHandler;
}
private static List<MySQLDatabase> updateList;
private static String host;
private static String database;
private static String username;
private static String password;
#Override
public void run() {
while (true) {
for (MySQLDatabase database : updateList) {
try {
if (database.getConnection() == null) {
database.connect();
} else {
database.ping();
}
database.cycle();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (Exception ex) {
}
}
}
}
private static void loadProperties() {
Properties p = new Properties();
try {
p.load(new FileInputStream("./sql.ini"));
host = p.getProperty("host");
database = p.getProperty("database");
username = p.getProperty("username");
password = p.getProperty("password");
} catch (Exception ex) {
System.out.println("Error loading MySQL properties.");
}
}
public static String getHost() {
return host;
}
static {
loadProperties();
updateList = new ArrayList<MySQLDatabase>();
updateList.add(new MySQLDonation(host, database, username, password));
}
}
MySQLDonation
package net.gielinor.network.sql.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.gielinor.game.model.player.Client;
import net.gielinor.game.model.player.PlayerHandler;
import net.gielinor.game.model.player.PlayerSave;
import net.gielinor.network.sql.MySQLDatabase;
public final class MySQLDonation extends MySQLDatabase {
public MySQLDonation(String host, String database, String username, String password) {
super(host, database, username, password);
}
#Override
public void cycle() throws SQLException {
ResultSet results = query("SELECT * FROM `gieli436_purchases`.`donations`");
if (results == null) {
return;
}
while (results.next()) {
String username = results.getString("username").replace("_", " ");
System.out.println("name=" + username);
Client client = (Client) PlayerHandler.getPlayer(username.toLowerCase());
System.out.println(client == null);
if (client != null && !client.disconnected) {
int creditamount = results.getInt("creditamount");
if (creditamount <= 0) {
continue;
}
handleDonation(client, creditamount);
query(String.format("DELETE FROM `gieli436_purchases`.`donations` WHERE `donations`.`username`='%s' LIMIT 1", client.playerName.replaceAll(" ", "_")));
}
}
}
#Override
public void ping() {
super.ping("donations", "username");
}
private void handleDonation(Client client, int creditamount) throws SQLException {
client.credits = (client.credits + creditamount);
client.sendMessage("Thank you for your purchase. You have received " + creditamount + " store credits.");
PlayerSave.save(client);
}
}
The exception occurs here: in the while loop within MySQLDonation and the actual stacktrace is this:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7077)
at net.gielinor.network.sql.impl.MySQLDonation.cycle(Unknown Source)
at net.gielinor.network.sql.MySQLHandler.run(Unknown Source)
With this information let me say that this does work, I get my message and what not in-game but it repeats, like the user is never removed from the query so it gives them infinite rewards. If you need any more information feel free to ask.
When you run the Delete query, you use the same Statement that was used in the Select query. When you re-execute on the same Statement, the previous ResultSet gets closed.
To avoid this, you should create a new Statement everytime you execute a query. So remove statement = connection.createStatement(); from the connect() method in MySQLDatabase class, and replace all statement in that class to connection.createStatement(). You may also choose to delete the private variable statement altogether.
You can read more about it here.
this error is some time occur when we use same statement object for diff. types
check Statement objectsss;
I have been working in web services with java. I built the wsd before the Java (Top-Down). The problem is that I made some classes to request data from a MySql database. In the method of SOAPImpl I create an Object of the class Usuario, but when I test the service with SOAP UI, it shows an NullPointerException.
This is the code
DataBase.java
package negocio;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DataBase
{
private String conexion;
private String user;
private String pass;
Connection conexionBase;
Statement estado;
DataBase()
{
this.conexion = "jdbc:mysql://localhost/agua";
this.user = "1234";
this.pass = "1234";
this.preparaDB();
}
public void preparaDB()
{
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
this.conexionBase = DriverManager.getConnection (conexion, user, pass);
estado = conexionBase.createStatement();
}
catch(SQLException e)
{
System.out.println(e.toString());
}
}
public Statement getEstado()
{
return estado;
}
}
Usuario.java
package negocio;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Usuario extends DataBase{
private String clave;
private String nombre;
private String paterno;
private String materno;
public Usuario()
{
super();
}
public Usuario(String clave)
{
super();
cargaUsuarioClave(clave);
}
public void cargaUsuarioClave(String clave)
{
String query = "SELECT * FROM usuario WHERE numeroCliente = '" + clave + "'";
try
{
ResultSet resultado = this.getEstado().executeQuery(query);
while(resultado.next())
{
this.clave = resultado.getString("numeroCliente");
this.nombre = resultado.getString("nombre");
this.paterno = resultado.getString("paterno");
}
}
catch(SQLException e)
{
System.out.println(e.toString());
}
}
public String getClave()
{
return this.clave;
}
public String getNombre()
{
return this.nombre;
}
public String getPaterno()
{
return this.paterno;
}
public String getMaterno()
{
return this.materno;
}
}
AguaSaneamientoSOAPImpl.java
/**
* AguaSaneamientoSOAPImpl.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package org.example.www.AguaSaneamiento;
import java.rmi.RemoteException;
import negocio.Usuario;
public class AguaSaneamientoSOAPImpl implements org.example.www.AguaSaneamiento.AguaSaneamiento_PortType{
public org.example.www.AguaSaneamiento.ConsultarServicioPropiedadResponse consultarServicioPropiedad(org.example.www.AguaSaneamiento.ConsultarServicioPropiedadRequest parameters) throws java.rmi.RemoteException
{
return null;
}
public org.example.www.AguaSaneamiento.ConsultaServicioUsuarioResponse consultaServicioUsuario(org.example.www.AguaSaneamiento.ConsultaServicioUsuarioRequest parameters) throws java.rmi.RemoteException {
return null;
}
public org.example.www.AguaSaneamiento.InfoPagosUsuarioResponse infoPagosUsuario(org.example.www.AguaSaneamiento.InfoPagosUsuarioRequest parameters) throws java.rmi.RemoteException {
return null;
}
public org.example.www.AguaSaneamiento.InfoUsuarioResponse infoUsuario(org.example.www.AguaSaneamiento.InfoUsuarioRequest parameters) throws java.rmi.RemoteException
{
Usuario us = new Usuario("2");
InfoUsuario [] infoUser = new InfoUsuario[1];
infoUser[0] = new InfoUsuario("Enrique", "14 Sur", "345", "6");
InfoUsuarioResponse infoRes = new InfoUsuarioResponse(infoUser);
return infoRes;
}
}
I tested the Usuario class and it works, but, when I call the cargaUsuarioClave inside the infoUsuario method, the webservice returns a JavaNullPointException. This is the response.
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server.userException</faultcode>
<faultstring>java.lang.NullPointerException</faultstring>
<detail>
<ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">SERVER</ns1:hostname>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
I don't know what can be wrong.
I have resolved the problem, It wasn't the source code, the problem was the connector file; I needed to copy tath file into the lib folder of my project.
I have a program that is grabbing prices from web pages, and then finds the difference of that price from the last grabbed price, and then it sends that value to my MySQL Database.
Things to note before looking at the code:
The actual price, which is a double, does get sent and is entered into my Database correctly, although my priceChange variable is not. I have tried changing it to a BigDecimal and that made not changes.
PriceGrabber.java (sloppy right now, I know. I'm going to slim the code down eventually. once I get my core functions working.)
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.TimerTask;
import java.util.Date;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.*;
import java.lang.*;
import java.net.URL;
import java.io.*;
public class PriceGrabber extends TimerTask{
#Override
public void run() {
try {
if(Coinbase.getLastPrice() == Variables.getCoinbase()){
System.out.println();
}else {
System.out.println("Price Change Detected in Coinbase!");
System.out.println("Price Change: " + (Variables.getCoinbase() - Coinbase.getLastPrice()));
Coinbase.setLastPrice(Variables.getCoinbase());
Variables.addPrice(Variables.getCoinbase(), "Coinbase", (Variables.getCoinbase() - Coinbase.getLastPrice()));
}
if(BTCE.getLastPrice() == Variables.getBTCE()){
System.out.println();
}else {
System.out.println("Price Change Detected in BTC-E!");
System.out.println("Price Change: " + (Variables.getBTCE() - BTCE.getLastPrice()));
BTCE.setLastPrice(Variables.getBTCE());
Variables.addPrice(Variables.getBTCE(), "BTC-e", (Variables.getBTCE() - BTCE.getLastPrice()));
}
if(BitStamp.getLastPrice() == Variables.getBitStamp()){
System.out.println();
}else {
System.out.println("Price Change Detected in BitStamp Market!");
System.out.println("Price Change: " + (Variables.getBitStamp() - BitStamp.getLastPrice()));
BitStamp.setLastPrice(Variables.getBitStamp());
Variables.addPrice(Variables.getBitStamp(), "Bitstamp", (Variables.getBitStamp() - BitStamp.getLastPrice()));
}
if(Bitfinext.getLastPrice() == Variables.getBitfinext()){
System.out.println();
}else {
System.out.println("Price Change Detected in Bitfinext!");
System.out.println("Price Change: " + (Variables.getBitfinext() - Bitfinext.getLastPrice()));
Bitfinext.setLastPrice(Variables.getBitfinext());
Variables.addPrice(Variables.getBitfinext(), "Bitfinext", (Variables.getBitfinext() - Bitfinext.getLastPrice()));
}
//Variables.printPrices();
} catch (IOException e) {
}
}
}
Variables.java
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.TimerTask;
import java.util.Date;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.*;
import java.lang.*;
import java.net.URL;
import java.io.*;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
public class Variables {
public static final String DB_URL = "jdbc:mysql://URL TO DB";
// Database credentials
public static final String USER = "username";
public static final String PASS = "password";
//Web Elements
public static URL url = null;
public static Document page = null;
public static Element priceElement = null;
public static Document doc = null;
public static String price;
public static String priceString;
public static String timeStamp;
//Different Market URL's
public static String coinbaseURL = "https://bitcoinwisdom.com/markets/coinbase/btcusd";
public static String btceURL = "https://bitcoinwisdom.com/markets/btce/btcusd";
public static String bitstampURL = "https://bitcoinwisdom.com/markets/bitstamp/btcusd";
public static String bitfinextURL = "https://bitcoinwisdom.com/markets/bitfinex/btcusd";
//Sets the URL
public static void setURL(String siteURL) throws MalformedURLException, IOException{
url = new URL(siteURL);
}
public static Double getCoinbase() throws IOException{
try{
setURL(coinbaseURL);
page = Jsoup.parse(url, 5000);
if(page.select("div.green").first() == null){
priceElement = page.select("div.red").first();
}else{
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
}catch(IOException e) {
System.out.println("something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public static Double getBTCE() throws IOException{
try{
setURL(btceURL);
page = Jsoup.parse(url, 5000);
if(page.select("div.green").first() == null){
priceElement = page.select("div.red").first();
}else{
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
}catch(IOException e){
System.out.println("oops! Something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public static Double getBitStamp() throws IOException {
try {
setURL(bitstampURL);
page = Jsoup.parse(url, 5000);
if (page.select("div.green").first() == null) {
priceElement = page.select("div.red").first();
} else {
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
} catch (IOException e) {
System.out.println("oops! Something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public static Double getBitfinext() throws IOException {
try {
setURL(bitfinextURL);
page = Jsoup.parse(url, 5000);
if (page.select("div.green").first() == null) {
priceElement = page.select("div.red").first();
} else {
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
} catch (IOException e) {
System.out.println("oops! Something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
//***********************************************************************************\\
//TODO:******************************************************************************\\
//TODO: SEARCH FOR QUEUE SYSTEM TO AVOID HAVING TO RECONNECT FOR EACH ADDITION \\
//TODO:******************************************************************************\\
//***********************************************************************************\\
public static void addPrice(Double price, String market, Double priceChange){
java.sql.Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
String query = " insert into prices (market, price, pricechange, time_of_change)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, market);
preparedStmt.setDouble (2, price);
preparedStmt.setDouble(3, priceChange);
preparedStmt.setTimestamp(4, sqlDate);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}//end main
}
I'm going to show you the source of Coinbase.java, it is the exact same as the other classes (BTCE.java, Bitfinext.java, etc.) Just to save space
Coinbase.java (Same as other market classes)
/**
* Created by Sullivan4653 on 12/8/2014.
*/
public class Coinbase {
public static double lastPrice = 0.0;
public static void setLastPrice(double price){
lastPrice = price;
}
public static double getLastPrice(){
return lastPrice;
}
}
**Finally my MySQL Information: **
My MySQL Database/Table and columns all work except my priceChange one. The value-type is set to Double. Default value = null. That is the SAME as my price column, which seems to be working because I'm getting values of the prices. (AKA not 0 every time like my PriceChange column)
My question is, why is this double now showing in my MySQL Database?
I apologize for the length of the post but I want to make sure I don't leave out any details that may help someone understand the problem. I've been struggling with it for a few days now and can't find the error!
Thanks!
Stop using static classes, go deeper into Java if you already want to make stuff like this :)
Also, if you want to provide code to others, please use some nice naming conventions, instead of making everything look like default variables (IE coinbaseURL, which should be something like COINBASE_URL, based on your modifiers).
In your code you're declaring the old value with a new value, so you're overriding it (you cannot use it anymore, because it changed to the new one).
Here's what I mean:
Coinbase.setLastPrice(Variables.getCoinbase());
Variables.addPrice(Variables.getCoinbase(), "Coinbase", (Variables.getCoinbase() - Coinbase.getLastPrice()));
I've simplified your code and improved it, this should work.
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* #author JKetelaar
*/
public class PriceGrabber implements Runnable {
private Coinbase coinbase;
private Variables variables;
public PriceGrabber(){
this.coinbase = new Coinbase(0);
this.variables = new Variables();
this.variables.connect();
}
public static void main(String[] args){
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new PriceGrabber(), 0, 10, TimeUnit.SECONDS);
}
#Override
public void run() {
try {
if (coinbase.getPrice() == variables.getCoinbase()) {
System.out.println("No changes found for Coinbase...");
} else {
System.out.println("Price Change detected in Coinbase!");
Double cbase = variables.getCoinbase();
Double cprice = coinbase.getPrice();
System.out.println("Old price: " + cprice + "\nNew price: " + cbase + "\nPrice Change: " + (cbase - cprice));
coinbase.setPrice(cbase);
variables.addPrice(cbase, "Coinbase", (cprice - cprice));
}
} catch (IOException ignored) {
}
}
}
-
public class Coinbase {
private double price = 0.0;
public Coinbase(double price) {
this.price = price;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
-
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
public class Variables {
public static final String DB_URL = "jdbc:mysql://160.153.49.168:3306/btcprogram";
// Database credentials
public static final String USER = "sully";
public static final String PASS = "asweq123e";
//Web Elements
public static URL url = null;
public static Document page = null;
public static Element priceElement = null;
public static Document doc = null;
public static String price;
public static String priceString;
public static String coinbaseURL = "https://bitcoinwisdom.com/markets/coinbase/btcusd";
private Connection connection;
//Sets the URL
public void setURL(String siteURL) throws IOException {
url = new URL(siteURL);
}
public Double getCoinbase() throws IOException {
try {
setURL(coinbaseURL);
page = Jsoup.parse(url, 5000);
if (page.select("div.green").first() == null) {
priceElement = page.select("div.red").first();
} else {
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
} catch (IOException e) {
System.out.println("something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public void addPrice(Double price, String market, Double priceChange) {
/**
* In your table set the time of change to a default value, so the table will do the time itself.
* Makes it easier for you and doesn't get complicated if you want to get others to insert prices.
*/
this.query("INSERT INTO prices (market, price, pricechange) VALUES (?, ?, ?)", new Object[]{
price, market, priceChange
});
}
public ResultSet query(String q, Object[] args) {
if (connection == null) {
System.out.println("No connection to the database.");
return null;
}
try {
PreparedStatement preparedStatement = connection.prepareStatement(q);
for (int i = 1; i <= args.length; i++) {
if (args[i] instanceof Double){
preparedStatement.setDouble(i, Double.parseDouble(String.valueOf(args[i])));
}else{
preparedStatement.setString(i, String.valueOf(args[i - 1]));
}
}
if (q.toLowerCase().startsWith("select")) {
return preparedStatement.executeQuery();
} else {
preparedStatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
.getConnection("jdbc:mysql://160.153.49.168:3306/btcprogram?"
+ "user=sully&password=asweq123e");
if (!connection.isClosed()) {
System.out.println("Successfully connected to the database...\nReady for SQL queries!");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
Following is my servlet:
import java.io.IOException;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import connection.Connection;
#WebServlet("/Check")
public class Check extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
Connection con;
//PreparedStatement pstmt=con.prepareStatement("Insert into account_master(name,acct_opn_date,cif_id,address) values(?,?,?,?)");
PreparedStatement pstmt= con.prepareStatement("Insert into account_master(name,acct_opn_date,cif_id,address) values(?,?,?,?)");
}
Here in the last statement, I am getting error in Eclipse
**Multiple markers at this line
Watchpoint:Check [access and modification] - pstmt
The method prepareStatement(String) is undefined for the type
Connection**
Following is my connection class:
package connection;
import java.sql.*;
public class Connection {
public static void main(String args[])
{
String username="system";
String password="root";
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
try {
DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE",username,password);
//DriverManager.getConnection("jdbc:oracle:thin:system/root#localhost:1521:XE");
} catch (SQLException e) {
System.err.println("Problem in connection");
e.printStackTrace();
}
}
catch(ClassNotFoundException ex)
{
System.err.println("Error loading driver");
}
}
}
You are confusing the JDBC Connection class with your own connection class.
You can rename your connection class to a ConnectionBuilder class:
public class ConnectionBuilder {
String username="system";
String password="root";
public static Connection buildConnection () {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
try {
return DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE",username,password);
} catch (SQLException e) {
System.err.println("Problem in connection");
e.printStackTrace();
return null; // better throw an exception
}
} catch(ClassNotFoundException ex) {
System.err.println("Error loading driver");
return null; // better throw an exception
}
}
}
And your Check class should use this method:
PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(...);
I have a homework to retrieve a myqsl query and save it to a ArrayList , and then to link it to another class and then serialize it and send it through http,
In a scheme it would be
class Server{static class a {try{try{ try{arraylist1} }}}}
class b {var1,var2,link_to(arraylist1)}
then serialize class b and send it
i managed to take the sql query and save the objects in the ArrayList (objects created from class "Personat") through
if (rs != null) {
List<Personat> perList = new ArrayList<Personat>();
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("var1"));
per.setName(rs.getString("var2"));
per.setAmount(rs.getInt("var3"));
perList.add(per);
}
}
Where rs=ResultSet object
but i cant access the ArrayList from class b so i can serialize it. I have tried to make it static (nothing ,it cant be linked).I have tried to make a getter (yet nothing eclipse wont let me as i automatically generate them).
So i don't know what i should do ! Can someone help me ? Or does anyone have any idea?
i have tried to search google for this but as you can see is a little too specific so no results until now ....
here is my Server.java
package server2;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
private static List<Personat> perList = new ArrayList<Personat>();
//need to access this in the SendRes class
public List<Personat> getPerList() {
return perList;
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
}
static public class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
//
final String url = "jdbc:mysql://localhost/httpServer";
final String user = "root";
final String password = "";
try {
Send oin = (Send) ios.readObject();
int id = oin.getId();
String emri = oin.getName();
int amount = oin.getAmount();
int paid = oin.getPaid();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,
password);
try {
PreparedStatement s = con
.prepareStatement("INSERT INTO person(ID,Name,Amount,Paid) VALUES (?,?,?,?)");
s.setInt(1, id);
s.setString(2, emri);
s.setInt(3, amount);
s.setInt(4, paid);
s.executeUpdate();
ResultSet rs = s.executeQuery("SELECT * "
+ "from personat ORDER BY EmpId");
if (rs != null) {
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("ID"));
per.setName(rs.getString("Name"));
per.setAmount(rs.getInt("Amount"));
perList.add(per);
}
}
//here i need to send an SendRes object with the ArrayList inside it
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class SendResponse implements Serializable {
String gabim;
String gabimNr;
//link the arraylist from class server here
}
class Personat {
int ID;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
String Name;
int Amount;
}
Objects of type B can only access the public members of type A. To get access to your list you need to make it a public member of A. The typical way to do this is to use a private field and a public getter.
class A
{
private List<Personat> personList;
public List<Personat> getPersonList() { return personList; }
public void handle(HttpExchange t) throws IOException
{
// ...
personList = ...;
// ...
}
}
Note that by giving public access to your list you are also allowing clients to modify the contents of the list. You may prefer to give them a copy of the list if this is not desirable.
On a slightly unrelated note, if you three nested try blocks in a single method then that method is probably too complex and should be refactored into smaller methods.