Java compilation with 2 classes - java

This is some very simple java OOP but I haven't done this in a while...I'm getting a "symbol not found" error when referencing one java class from another
Class #1:
package toaV2;
import java.sql.Connection;
public class vehicle_model
{
public db_model DB;
public Connection conn;
public static void main(String[] args) {
vehicle_model v = new vehicle_model("system");
}
public vehicle_model(String sys) {
DB = new db_model(sys);
conn = DB.connect();
if(conn != null) {
System.err.println("Got a connection.");
}
else {
System.err.println("Couldn't get a connection...");
}
}
}
Class #2:
package toaV2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class db_model
{
private static String driver = "com.mysql.jdbc.Driver";
private static String dbUser = "user";
private static String dbPass = "pass";
private static String dbUrl = "jdbc:mysql://url";
private static String system;
public static Connection conn;
public db_model(String sys)
{
system = sys;
}
public static Connection connect()
{
conn = null;
try
{
String dbName = system.toUpperCase();
String dbHost = dbUrl + dbName;
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(dbUrl, dbUser, dbPass);
}
catch(Exception e)
{
System.err.println("Exception: " + e.getMessage());
}
return conn;
}
}
And the errors I get on compilation:
$ javac vehicle_model.java
vehicle_model.java:10: cannot find symbol
symbol : class db_model
location: class toaV2.vehicle_model
public db_model DB;
^
vehicle_model.java:24: cannot find symbol
symbol : class db_model
location: class toaV2.vehicle_model
DB = new db_model(system);
^
2 errors

you need to provide the classpath to the other java files when you're compiling.
i.e. javac -classpath path/to/class2 vehicle_model.java

You must compile your two files in the same command, like
javac vehicle_model.java db_model.java

Related

Is it possible to reuse a connection statement without closing it? [duplicate]

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;

Constructing and object of a class and calling it's methode in Java

Trying to program that can read a MySql database. Somehow I cannot call the methode connect(). It says:
Error: cannot find symbol"
connect.connnect();
_______^
What I'm trying to do is to have the connnect and getData method in different classes, so I can also use the connect class seperately for other projects.
Main:
import java.sql.*;
public class Main {
public static void main( String argv[]) {
Connect connect = new Connect();
Connect.connect();
GetData getdata = new GetData();
getdata.getdata();
}
}
Connect:
import java.sql.*;
public class Connect{
public Connection con;
public Statement st;
public ResultSet rs;
public connect(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/leichtathletik","root","");
st = con.createStatement();
}catch(Exception e1) {
System.out.println("Error: "+e1);
}
}
}
GetData:
import java.sql.*;
public class GetData {
public void getData() {
try {
String query = "select * läufer";
rs = st.esecuteQuery(query);
while (rs.next()) {
String vorname = rs.getString("vorname");
String nachname = rs.getString("nachname");
System.out.println(vorname+" "+nachname);
} // end of while
} catch(Exception e2) {
System.out.println("Error: "+e2);
}
}
}
The "connect"- method on the Connect class needs to have a type.
https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html , can be helpful.
Further more, the youtuber (https://www.youtube.com/channel/UCiczh_Q-rC7VhMV0x6__dBw) can maybe help you get started with java.

Mysql database Exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
i am a beginner in java i am trying to use mysql database i have downloaded mysql-connector-java-5.1.23-bin.jar file from mysql.com and i have added this jar file to in my build path of my project but there is an error in the following code
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
package com.example.demo;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try
{
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}
}
Wrong classes
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
should be
import java.sql.Connection;
import java.sql.Statement;
In fact, java decouples everything from a specific database engine. One never should need an import of MySQL (or ProgressSQL or ...) classes.
To have those classes available at run-time, the first thing after the try, before getting the connection would be:
Class.forName("com.mysql.jdbc.Driver");
This technique would allow reading all strings from a configuration file, and writing database independent code.
Missing: conn = ...
conn = DriverManager.getConnection(CONN_STR, userName, userpwd);
package com.example.demo;
import java.sql.*;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}

Trying to use jdbc driver for postgresql but it's not working

I have added the jdbc driver to my classpath as far as I know i.e. I added the following to my .profile
export CLASSPATH=$CLASSPATH:location/to/the/jarfile.jar
When I compile my java program I always get this error
javac v9.java
v9.java:8: <identifier> expected
Class.forName("org.postgresql.Driver");//load the driver
^
v9.java:8: illegal start of type
Class.forName("org.postgresql.Driver");//load the driver
^
2 errors
This is driving me insane, any help would be awesome. I'm using Mac OS X Snow Leopard
The java program is here
import java.sql.*;
public class v9
{
String dbURL = "jdbc:postgresql:mydb";
String user = "UserName";
String password = "pswd";
C try
{
Class.forName("org.postgresql.Driver");//load the driver
// Connect to the database
Connection DBconn = DriverManager.getConnection( dbURL, user, password );
}
catch (Exception e)
{
e.printStackTrace();
}
}
Try this - you need a method somewhere:
import java.sql.Connection;
import java.sql.DriverManager;
public class V9
{
public static final String driver = "org.postgresql.Driver";
public static final String url = "jdbc:postgresql://localhost:5432/party";
public static final String username = "pgsuper";
public static final String password = "pgsuper";
public static void main(String [] args)
{
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println(conn.getMetaData().getDatabaseProductName());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Connecting to MySql on Mac: No suitable driver error

I am getting the error: java.sql.SQLException: No suitable driver
I have imported the .jar file that is available here http://dev.mysql.com/downloads/mirror.php?id=13598
I am using Eclipse.
I am connecting to the DB with this code:
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBCon {
private static final String host = "jdbc:mysql://localhost";
private static final String port = "3306";
private static final String db = "mydb";
// private static final String user = "root";
// private static final String pwd = "";
private static final String user = "myusername";
private static final String pwd = "mypwd";
public Connection getCon() {
Connection con = null;
try {
String url = host + ":" + port + "/" + db;
con = DriverManager.getConnection(url, user, pwd);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
I then query the DB with this code:
package dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.Connection;
import model.ClassPojo;
public class ARCSDao {
public ArrayList<ClassPojo> viewClasses() throws SQLException{
ArrayList<ClassPojo> classList = new ArrayList<ClassPojo>();
DBCon db = new DBCon();
Connection con = db.getCon();
Statement stmt;
ResultSet rs;
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM classes");
while(rs.next()){
ClassPojo aClass = new ClassPojo();
rs.getString("class_name");
rs.getString("class_uri");
classList.add(aClass);
}
return classList;
}
}
Add
Class.forName("com.mysql.jdbc.Driver").newInstance();
before
con = DriverManager.getConnection(url, user, pwd);
if this doesn't work double check that the jdbc driver (jar file) is included in your classpath

Categories