I'm currently writing a jdbc client-server socket application in java. I've been having a bit of trouble initializing jdbc as i'm not using an ide, just a text editor and jdk. I have put my jdbc driver in my jdk and jre classpaths C:\Program Files\Java\jdk1.6.0_20\jre\lib\ext and \jre\lib\ext . I also renamed the jar to com.mysql.jdbc.driver , but I have still had no luck. Is this a problem with the driver not being found or is it something else?
Here is my error:
C:\Users\imallin\My Documents>java Provider
Waiting for connection
Connection received from 127.0.0.1
server>Hi welcome to the Cyfieithu Eadar-Theangachadh translation server, please
enter a command. Type cmd to see a list of commands
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Provider.insertData(Provider.java:82)
at Provider.run(Provider.java:40)
at Provider.main(Provider.java:118)
Here is my code:
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Provider{
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Connection con;
Provider(){}
void run()
{
Console c = System.console();
if (c == null) {
System.err.println("No console.");
System.exit(1);
}
try{
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Hi welcome to the Cyfieithu Eadar-Theangachadh translation server, please enter a command. Type cmd to see a list of commands");
//4. The two parts communicate via the input and output streams
do{
try{
insertData();
message = (String) in.readObject();
System.out.println("client>" + message);
if (message.equals("register"))
sendMessage("first name?");
String firstName = (message);
sendMessage("first name = " + firstName);
insertData();
if (message.equals("listlanguages"))
sendMessage("English \n Thai \n Geordia \n Gaelic \n Welsh \n Gaelic \n Urdu \n Polish \n Punjabi \n Cantonese \n Mandarin");
if (message.equals("bye"))
sendMessage("bye");
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
private void insertData()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost/translator","root","");
String sql = "Insert INTO users (ID, firstName) VALUES ('123','123')";
Statement statement = con.createStatement();
statement.execute(sql);
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Provider server = new Provider();
while(true){
server.run();
}
}
}
Like other answers have hinted already, the jdbc Jar is not on your classpath.
To fix this, you need to declare, when running your Java main file, that it should use that Jar, by doing:
java -cp "nameOfJar.jar" Provider
This is assuming that your jar is on the same dir as your Provider file, if not you should specify the path to it.
It's totally optional, but I like having a directory named "lib" where I put all the jars I need to run my project, then you can add to classpath by doing:
java -cp "./lib/*;." NameOfJavaClassWithMain
Ultimately, you might end up having several directories or jars that you need to add to your classpath, you do this by using the ; (: in linux) separator, like:
java -cp "./lib/*;./conf/configurationFile.properties;." NameOfJavaClassWithMain
If your .class is not on one of the Jars, you might have to add the local directory to your classpath:
java -cp "./lib/*;." NameOfJavaClassWithMain
If you have a package declaration on your class (you should), you need to reference the class by that fully classified name (package+ClassName), like so:
java -cp "./lib/*;." my.package.NameOfJavaClassWithMain
Ultimately your classpath for jdbc is not set.
This is what I do ( a bad practice )
extract your jar file. (say you are working in home directory ~, and the name of directory where jar file is extracted is odbc)
then set your classpath to
export CLASSPATH=~/odbc:
( do not forget to add : after the path ;-) )
Oh could not realize that you are working on windows machine.
Then
set environment variable ( create if does not exists ) CLASSPATH to c:\odbcdir
or other-way is to use java -cp pathToJAR.jar Main.
The MySQL Driver jar is not on the classpath. You need to fix this, by using the -cp argument tojava.
Related
I have a JAR file that doesn't connect to the database even though it connects just fine in the IDE. I'm stuck and I don't know where to go from here. I am using Java 8 in IntelliJ trying to run SQLite.
Here is the code for the Database class.
private static Connection connection = null;
private static boolean connected = false;
static void connect() {
String driver = "org.sqlite.JDBC";
String db = "schedulerDB";
String path = "lib\\";
String url = "jdbc:sqlite:";
try {
Class.forName(driver);
connection = DriverManager.getConnection(url + path + db);
printInfo("Connected to database : " + db);
connected = true;
} catch (SQLException e) {
printError(1100, "Could not connect to database", e);
} catch (ClassNotFoundException e) {
printError(1101, "Driver not found error", e);
}
}
When I run the JAR file in the terminal, I get:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
Please help me.
Added e.printStackTrace(); as requested:
org.sqlite.SQLiteException: [SQLITE_ERROR] SQL error or missing database (no such table: user)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.throwex(DB.java:918)
at org.sqlite.core.NativeDB.prepare_utf8(Native Method)
at org.sqlite.core.NativeDB.prepare(NativeDB.java:134)
at org.sqlite.core.DB.prepare(DB.java:257)
at org.sqlite.jdbc3.JDBC3Statement.execute(JDBC3Statement.java:52)
at scheduler.Database.query(Database.java:337)
at scheduler.User.buildList(User.java:42)
at scheduler.User.<clinit>(User.java:85)
at scheduler.Main.start(Main.java:27)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Unknown Source)
Change the value of url to
url = "jdbc:sqlite::resource:"
Your exception is actually caused by a MalformedURLException. The reason you are getting this is because lib\schedulerDB is not a valid URL.
URLs must use forward slashes (/), on all systems—even Windows. This is a requirement of the URI specification itself. (A URL is a type of URI, so every URL must conform to the rules of a URI.)
Making your URL valid should do the trick:
String path = "lib/";
I am trying to connect to Oracle database using TNS.
The problem is that TNS alias contains dot, so when I am specifying url like this:
jdbc:oracle:thin:#TNS.ALIAS
I've got...
oracle.net.ns.NetException: Invalid connection string format, a valid format is: "host:port:sid"
...during creation of connection.
I know that dot character is a problem, because after removing it from tnsnames.ora file connection to database works.
My question is - is it possible to escape dot character somehow? Maybe there is some connection parameter that can be setup to allow dot character in alias? I would like to avoid removing dot from tnsnames.ora since i am getting the file from outside source.
Here are the options that I've already tried that gave me the same error:
jdbc:oracle:thin:#"TNS.ALIAS"
jdbc:oracle:thin:#\"TNS.ALIAS\"
jdbc:oracle:thin:#`TNS.ALIAS`
jdbc:oracle:thin:#TNS\.ALIAS - this one is not compiling
jdbc:oracle:thin:#TNS\\.ALIAS
jdbc:oracle:thin:#TNS.ALIAS
jdbc:oracle:thin:#TNS\".\"ALIAS
jdbc:oracle:thin:#TNS%2eALIAS
Here are the options that resulted with oracle.net.ns.NetException: could not resolve the connect identifier:
jdbc:oracle:thin:#TNSALIAS
jdbc:oracle:thin:#TNS-ALIAS
jdbc:oracle:thin:#TNS_ALIAS
Additional context:
I am trying to create Java's DataSource (OracleDataSource to be
strict) in Scala (it is Play Framework - but I am not using Play's
way of creation of DB connections - I am doing it manually)
I have SQL Developer that is using exactly the same tnsnames.ora file and it is working there
We are having C# applications that are using exactly the same tnsnames.ora file and it is working there (data source is defined like this: <add name="connectionName" connectionString="Data Source=TNS.ALIAS;"/>
You need set
System.setProperty("oracle.net.tns_admin","C:\\app\\product\\12.2.0\\client_1\\network\\admin");
set to the location of the tnsnames.ora
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnect {
public Connection connection;
public DBConnect() {
}
public void connect() throws Exception {
String connectString;
System.setProperty("oracle.net.tns_admin", "C:\\app\\product\\12.2.0\\client_1\\network\\admin");
Class.forName("oracle.jdbc.driver.OracleDriver");
connectString = "jdbc:oracle:thin:#esmdj.test";
System.out.println("Before DriverManager.getConnection");
try {
connection = DriverManager.getConnection(connectString, "scott", "tiger");
System.out.println("Connection established");
connection.setAutoCommit(false);
} catch (Exception e) {
System.out.println("Exception inside connect(): " + e);
e.printStackTrace();
}
}
public static void main(String[] args) {
DBConnect client = new DBConnect();
System.out.println("beginning");
try {
client.connect();
System.out.println("after Connected");
client.connection.close();
System.out.println("after close");
} catch (Exception e) {
try {
System.out.println("Exception : " + e);
client.connection.close();
e.printStackTrace();
} catch (Exception ex) {
System.out.println("Close Connection Exception : " + ex);
ex.printStackTrace();
}
}
}
}
C:\Program Files\Java\jdk1.8.0_73\bin>java -classpath . DBConnect
beginning
Before DriverManager.getConnection
Connection established
after Connected
after close
tnsnames.ora
esmdj.test =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = xxx.xxx.yyy.zzz)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = ESMD)
)
)
I've found the problem - I was using older Oracle driver (ojdbc7.jar for version 12.1.0.1) after change to newer one (ojdbc8.jar for version 12.2.0.1) lookup by TNS alias started to work - there was no need to escape anything
I'm trying to create simple socket application using sockets to send stream from linux (64x ArchLinux) to server (Windows XP).
Code I'm using I found on the internet, just to check if it is working. What is interesting the code works perfectly if I'm using Windows XP (server) and Win 8 (client), but when client is on ArchLinux it does not work. Is there some special way to connect Windows-Linux ?
Server.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Server_pzm {
public static void main(String args[]) {
String data = "Toobie ornaught toobie";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Client.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("192.168.224.78", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
// while (!in.ready()) {} line removed
System.out.println(in.readLine());
System.out.print("'\n");
in.close();
}
/* lines removed catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
} */
// added exception handling
catch(UnknownHostException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
}
EDIT
Sorry, I did not specify what I meant by not working. I meant I got an exception which later prints System.out.print("Whoops! It didn't work!\n"); as in the catch blok. Win 8 and Arch Linux are installed on the same laptop, while the code is on my dropbox folder in both systems (so the code is the same) - I will post the actual exception, after I get back to my laptop
EDIT 2:
I updated code and this is exception I got:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
java.net.ConnectException: Connection refused
This has two possible meanings.
There is nothing listening at the address:port you tried to connect to.
There is a firewall rule in the way.
More likely 1. Firewalls usually just drop the packets, which causes a connection timeout rather than a refusal.
Are you sure you can establish connection between those systems? I have compiled and run your code on Windows 7 and Linux Mint on Virtualbox and it works correctly.
What do you mean "It doesn't work"? Does it throw any exception? If you just don't have any output, try to run it again and wait about 30 seconds.
For me it's just a network problem. So you should also try to ping your windows machine from linux and then try to telnet to server.
Edit:
So we know it is a network problem. First try to ping ip server from Linux system.
ping 192.168.224.78
If it didn't work, you should check if both machines are in the same subnet 192.168.224.0 assuming the mask is 255.255.255.0. You need just to type ifconfig in console.
In next step you should try to disable windows firewall. Here is an instruction how to do that.
I know I'll feel like a tard when I figure this one out. I'm trying to do a very simple client/server and run it from the command line. It runs fine from Eclipse, but not from cmd. Here's the client:
package com.mycompany.pdr.client;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class SimpleClientSend {
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 11048;
String dataToSend = "HELLO SERVER";
System.out.println("> Trying to connect...");
System.out.println("> Opening connection to server [" + host + ":"
+ port + "]...");
Socket socket1Connection;
try {
socket1Connection = new Socket(host, port);
System.out.println("> Connected...");
System.out.println("> Trying to write data... [ " + dataToSend + " ]");
BufferedOutputStream bos = new BufferedOutputStream(
socket1Connection.getOutputStream());
/*
* Instantiate an OutputStreamWriter object with the optional
* character encoding. e.g. UTF-8
*/
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
// Writing to server
osw.write(dataToSend);
osw.flush();
System.out.println("> Writing to server done...");
socket1Connection.close();
} catch (UnknownHostException e) {
System.out.println(e.getLocalizedMessage());
System.out.println("Unknown Host. Please check if the server is running at the IP & port");
//e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getLocalizedMessage());
System.out.println("Could not send data. Giving up.");
//e.printStackTrace();
}
System.out.println("> End of connection...");
}
}
My directory structure is : (MyWorkspace)/myProject/com/mycompany/pdr/client
I run javac SimpleClientSend.java from inside the client folder, and I get a class file, no errors. I run java SimpleClientSend and I get a NoClassDefFound message:
Exception in thread "main" java.lang.NoClassDefFoundError: SimpleClientSend (wrong name: com/iai/pdr/client/SimpleClientSend)
I've tried using -cp . when I run java to follow the suggestions of every other article out there(but what's the point if . is already in my classpath?), I've tried running it from outside the client folder, everything just gives me the same error. In eclipse, all I had to do was paste the java files into a blank project and it ran. What am I doing wrong here?
You need to specify the full name of your class (including package).
java com.mycompany.pdr.client.SimpleClientSend
It is important that the base of the structure for your class(es) is included in your class path. Normally . is included, so if you run the command above when your are in myProject it should work.
If you are in another folder you should add the myProject to your class path, such as:
java -cp ...MyWorkspace/myProject com.mycompany.pdr.client.SimpleClientSend
The ... of course is since I don't know your full path.
I've set the classpath envoirenment but still get an error "Exception:com.mysql.jdbc.Driver"
Do you have any idea what might be wrong?
Here is my test code:
import java.sql.*;
public class JdbcExample1 {
public static void main(String args[]) {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///test", "root", "secret");
if(!con.isClosed())
System.out.println("Successfully connected to MySQL server...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}
Exception:com.mysql.jdbc.Driver
Is most probably not the full error message. I guess it's a ClassNotFoundException and you simply do not have the MySQL JDBC driver as part of your classpath.
When running your program, you need to list the driver as well
java -cp .;mysql-connector-java-5.1.7-bin.jar JdbcExample1
(This assumes JdbcExample1.class and the .jar file are in the current directory)
I've set the classpath envoirenment
Setting the CLASSPATH environment variable is not necessary anymore (actually it never has been necessary). As a matter of fact it creates more problems than it solves.
Use the above syntax to supply the path to your driver and run your program
As horse says, I'm pretty sure it's a 'ClassNotFoundException'.
To be sure add "e.printStackTrace();" in your catch-block.
Always best to get a stack trace.