Error while compiling java file with GCC - java

I wrote a small java program in Netbeans. It compiles and runs perfectly. But I also need to compile it in javac in Linux because this homework is tested there. Whenever I attempt, I get the following compile error message. Do you have any idea about this message?
/usr/lib64/gcc/x86_64-suse-linux/4.6/../../../../lib64/crt1.o: In function `_start':
/home/abuild/rpmbuild/BUILD/glibc-2.14.1/csu/../sysdeps/x86_64/elf/start.S:109: undefined reference to `main'
I just write the following line for import a library
import java.sql.*;
I am just using println except sql operations. The beginning of my code is below:
Connection conn = null;
try{
String username = ".....";
String password = "....";
String url = "jdbc:mysql://localhost:3306/.....";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
System.out.println("Database connection extablished.");
}
catch(Exception e){
System.out.println("Cannot connect to database server");
}
After this part of code, nothing special, just ordinary lines.

It seems that error may be because you're not defining a main method, and the compiler therefore can't find it.
However, I have to ask why you're using GCC? Normal JDK is available on Linux and should be your preferred choice unless you have a very good reason otherwise! If Netbeans isn't compiling your application on Linux then it's probably because you haven't set something up properly or installed the JDK - you can (and should) use the JDK rather than GCJ, which is now largely unmaintained.
You can either grab it through your package manager or download it separately here.

You don't need to (re-)compile it for linux. It's Java. The generated class file (from windows) will run on Linux and Windows, you just need a JRE or JDK on the target host.

Compile with javac, not GCC (or GCJ if you really want something "GCCish").

Related

H2 DB driver not in classpath

I'm trying to connect to my embedded H2 database via Java. I found various threads and tutorials on this and now have this code:
Connection con = null;
Properties connectionProps = new Properties();
connectionProps.put("user", "username");
connectionProps.put("password", "password");
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con = DriverManager.getConnection("jdbc:h2:~/test", connectionProps);
I got the "no suitable driver found for jdbc:h2:~/test" error message. I found the Class.forName(...) in some threads as a solution to this, but it doesn't seem to be working (ClassNotFoundException).
I read that the driver is probably not in my classpath, but don't really know what I need to do with that information. In the database view of IntelliJ the driver seems to work just fine (I can click reload drivers and it confirms the h2 driver). What am I doing wrong?
There are a couple ways to add to the classpath. I recommend trying to understand this page https://howtodoinjava.com/java/basics/java-classpath/ for more information on different strategies that have similar, but different results.
Probably the simplest way for just this project, would be to edit the "run configuration" that you are using, and add a new VM option:
–classpath /path/to/local/h2/driver.jar
Use an absolute path to the jar, and this will allow it to be present in the classpath when running it this way. In the link I shared, this is the same as adding the command line argument to the java or javac command, so this argument will work outside of intellij on the command line as well.
Edit:
Based on the comments, it seems like you might be using the %PROGRAMFILES% environment variable, with a fully qualified path.
Try this instead:
-classpath %PROGRAMFILES%\H2\bin\h2-1.4.200.jar
If you were to run the following command in your command prompt
echo %PROGRAMFILES%
I suspect you'd get the response:
C:\Program Files
Which is not the x86 version. So. Either use the environment variable and omit the part of the path it's value represents (eliminating the C:\ part)
or, if that's not the correct Program Files folder at all, then avoid it and try (note the quotes which are required because a folder has spaces in it's name):
--classpath "C:\Program Files (x86)\H2\bin\h2-1.4.200.jar"

Python 3.7 connecting to HSQLDB on MAC

Trying to connect to a HSQLDB Java database using python 3.7, jaydebeapi, and jpype. I tried the following
import jaydebeapi
UserName = "SA"
Password = ""
Java_Class = "org.hsqldb.jdbcDriver"
HSQL_Driver_Path = "/Hsqldb/driver/hsqldb.jar"
Database = "jdbc:hsqldb:/Hsqldb/database/OneDatabase"
jaydebeapi.connect(Java_Class,Database,[UserName,Password],jars=HSQL_Driver_Path)
and it resulted in the following error
java.lang.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class org.hsqldb.jdbcDriver not found
google states that this is a classpath error and I need to add a class path to fix.
edit: Details of setup: Mac, anaconda, python 3.7
I tried something similar in R using the RJDBC library and was able to connect just fine.
PathDriver = "/Hsqldb/driver/hsqldb.jar"
JDBCDriver = "org.hsqldb.jdbcDriver"
drv <- JDBC(JDBCDriver,PathDriver)
# Connect to Database
DatabaseP <- "jdbc:hsqldb:file:////Hsqldb/database/OneDatabase"
Con <- dbConnect(drv,DatabaseP,"SA","")
edit: Details of setup: Mac, R, Rstudio
I separated R from Anaconda as Anaconda was blocking many of the libraries I wanted to use.
This is probably apples to oranges, but why does python need a classpath set when R performs the function just fine? and how does one set a class path for HSQLDB for python?
When starting JPype it either takes the classpath from the environment variable CLASS_PATH or from a manually specified classpath defined using the jpype.startJVM(classpath="...") command. This command is likely part of the jaydebeapi api if you don't have to call it directly from JPype.
I assume that R defines its own classpath internally so there may just be differences in the what is being seen from the JVM. This could include a different JVM is being selected, the classpath including different locations, or in some cases if the driver has a native portion such as MS SQLServer the library path may also not be correct. In order for the JDBC driver to load all piece need to be found including the jar, support jars and native shared libraries. If all else fails manually try to load the java class using Class.forname. It may provide you with further diagnostics as to which piece is missing.

Java SQLite3 Connection Failing

I am having some trouble connecting my java script to my SQLite3 database.
I have my directory holding my script as followed
C:/PROG/JavaPROG/programs/java_database
Inside this directory I have 3 files
Query.java, Query.class and the database query.db
My java code looks as followed
import java.sql.*;
public class Query3 {
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:C:/PROG/JavaPROG/programs/java_database/query.db");
System.out.println("Connection Success");
} catch(Exception log) {
System.out.println("Connection Failed: " + log);
}
}
}
my classpath does contain
C:\Program Files\Java\jdk1.8.0\bin
and inside that bin directory is the sqlite jdbc driver
sqlite-jdbc-3.7.2.jar
I can connect my script to PostgreSQL database but I can't see why it isn't connecting to the SQLite3, I am getting the following error message
java.lang.ClassNotFoundException: org.sqlite.JDBC
have I done something wrong?
You need to explicitly provide the sqlite-jdbc-3.7.2.jar file in your classpath while compiling and running your classes using the -cp option. The java and javac commands will only look for .class files in the classpath and not jars.
Try this :
javac -cp <path_to_jar/sqlite-jdbc-3.7.2.jar>;. <your_class_name>.java
And if you have more than one thirdparty library, you can use a wildcard :
javac -cp <path_to_jar/*>;. <your_class_name>.java
Note that ; is the separator used in Windows. If you are on unix based systems, you need to use : instead of ;. Java maybe platform independant but the java and javac commands are not.
Also note that the . tells the java and javac commands to look in the current directory for classes. Don't forget to provide the classpath to the jars when running your program using the java command.
I have found the answer to fix this.
compile the script as normal
javac Query.java
Then specify the driver when executing
java -classpath ".;sqlite-jdbc-3.7.2.jar" Query
And it will run fine

Java JDBC | Cannot run from console

I have developed a program where I do some database connections and send some queries with JDBC.
I have used MySQL, NetBeans 6.9 under Ubuntu 11.04 as platform. When I run the app from NetBeans, it works perfectly but when I try to run it from terminal I get SQL Exception. This is the function that produces that SQL Exception. The program terminates before "Establish is ending" line.
public Connection Establish(String iname, String ipassword) throws SQLException
{
System.out.println("Establish...");
if(conn == null)
{
conn = DriverManager.getConnection("jdbc:mysql://localhost/ANU",
iname, ipassword);
}
else
System.out.println("Connection Already Established!");
System.out.println("Establish is ending...");
return conn;
} // End of Establish
Make sure the MySQL Connector .jar file is in your classpath environment variable. IDEs, like NetBeans, sometimes help you out with putting .jar files in the classpath while you're in the IDE. You'll either need to run your app with the -cp option, or add it to your classpath environment variable.

NoSuchPortException using RXTX Java library on Windows?

I have followed the instructions to setup rxtx on windows from http://www.jcontrol.org/download/readme_rxtx_en.html.
What I did exactly was copy rxtxSerial.dll to "C:\Program Files\Java\jdk1.6.0_07\jre\bin"
and copied RXTXcomm.jar to "C:\Program Files\Java\jdk1.6.0_07\jre\lib\ext"
(my JAVA_HOME variable is set to C:\Program Files\Java\jdk1.6.0_07\jre)
I also added RXTXcomm.jar to my eclipse project.
But when I run it, it still says "NoSuchPortException"
Devel Library
=========================================
Native lib Version = RXTX-2.0-7pre1
Java lib Version = RXTX-2.0-7pre1
java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver
gnu.io.NoSuchPortException
at gnu.io.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:218)
at TwoWaySerialComm.connect(TwoWaySerialComm.java:20)
at TwoWaySerialComm.main(TwoWaySerialComm.java:107)
In my java file, I tell it:
try
{
(new TwoWaySerialComm()).connect("COM4");
}
and I've also tried the Java Comm API. Both cannot recognize my serial port but I am sure I followed the instruction correctly. There files are there.
Does anybody have any idea what it could be?
Try putting rxtxSerial.dll in
C:\Program Files\Java\jdk1.6.0_07\jre\lib\bin
^^^
you can use
CommPortIdentifier.getPortIdentifiers()
to identify all possible ports your system finds.
I am not too familiar with RXTX, but is this normal?
java.lang.ClassCastException: gnu.io.RXTXCommDriver cannot be cast to gnu.io.CommDriver thrown while loading gnu.io.RXTXCommDriver
Otherwise maybe the problem is not with the port itself after all, but something with the classes themselves?
Just a guess.
You can also try an alternative solution that was specifically implemented for Windows. There should be plenty available, one of them you can get from http://www.caerustech.com/JCommWin32.php
Shultz
It may be that your system does not have a COM4 defined or it's not accessible. It's hard to guess what may be wrong, because you haven't posted you port init code - what you posted looks like wrapper code.
Here is my working init code using the javax.comm API (but using SerialPort from serialio.com):
// name comes from config and is "COM1", "COM2", ...
SerialPort port=(SerialPort)CommPortIdentifier.getPortIdentifier(name).open("YourPortOwnerIdHere",5000); // owner and ms timeout
port.setSerialPortParams(bau,dtb,stb,par);
port.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN|SerialPort.FLOWCONTROL_RTSCTS_OUT);
port.enableReceiveTimeout(1000);
Hopefully this points you in the right direction.
I agree that you're problem looks like a ClassCastException and not the other.
For windows, I'm using "Windows Java Serial Com Port Driver" at http://www.engidea.com/blog/informatica/winjcom/winjcom.html and it is much easier for me to set up.
In either case, you want the DLL in the BIN directory, not LIB\BIN as was suggested. At least that's what's working for me. I'm using NetBeans and I've also found it helpful to put the jar and dll into various bin and lib\ext folders in the JDK.
Note that if you have multiple versions of the JRE on your machine, you might not be using the one that you think you are using. Also, as a practical matter I've found it more helpful to just copy both the jar and dll into the various bin and lib\ext folders. Makes it just a paste, paste, paste operation.
For windows, I recommend "Windows Java Serial Com Port Driver" because it solved my problems with USB serial ports. I had fits with RXTX because it would crash when the USB was unplugged. winjcom solved that problem and others as well. It has very helpful error exceptions.
Also, make sure your serial drivers are up-to-date. Downloading an update fixed my other bug.
-Stosh
I also had a problem when closing the serialPort within the serialEvent function.
Maybe it's a deadlock problem, where the close method waits forever for serialEvent's lock to be released.
Starting a new thread to close the port worked for me.
For your question, my code is the following:
if (idPuerto == null)
{
formulario = form;
boolean encontrado = false;
listaPuertos = CommPortIdentifier.getPortIdentifiers();
while( listaPuertos.hasMoreElements() && encontrado == false )
{
idPuerto = (CommPortIdentifier)listaPuertos.nextElement();
//System.out.println(idPuerto.getName());
if( idPuerto.getPortType() == CommPortIdentifier.PORT_SERIAL )
{
if( idPuerto.getName().equals(RFIDBascApp.ComBasc) )
{
encontrado = true;
logger.AddInfoUser("Puerto serie encontrado");
}
}
}
You had NoSuchPortException, so first of all iterate on all available ports!
import gnu.io.CommPortIdentifier;
import java.util.Enumeration;
public class ListAvailablePorts {
public void list() {
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
while(ports.hasMoreElements()){
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
System.out.println(port.getName());
}
}
public static void main(String[] args) {
new ListAvailablePorts().list();
}
}
#Pinheiro you might want to take a look at this

Categories

Resources