Java Rmi database connection? - java

I am trying to get data from mysql database by rmi,
When the client request the service from the server and trying to connect to db to get data
NO Suitable driver Exception rise !
or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
(Implementation Class)imp.java:
public class imp extends java.rmi.server.UnicastRemoteObject implements inter {
...
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
public String getName() throws java.rmi.RemoteException {
String name = "none";
try {
PreparedStatement ps = con.prepareStatement("select ....");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString("f_name");
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return name;
}
}
(Interface)inter.java:
public interface inter extends java.rmi.Remote {
public String getName() throws java.rmi.RemoteException, SQLException;
}
(Server)Server.java:
public Server() throws RemoteException, MalformedURLException {
server_object = new imp();
Naming.rebind("rmi://localhost:1099/myserv", server_object);
}
(Client) client.java:
myobject = (inter) Naming.lookup("rmi://localhost:1099/myserv");
myobject.getName();
I Put the mysqlconnector library in the folder of classes
Any Help?

The exception :java.lang.ClassNotFoundException: com.mysql.jdbc.Driver,causes whenever we forget to add jar file for mysql connector. pls add mysql connector jar file to your projects classpath, and run it.
Edited:
you can download it from here : http://code.google.com/p/find-ur-pal/downloads/detail?name=mysql-connector-java-5.1.18-bin.jar& or from here : http://dev.mysql.com/downloads/connector/j/5.0.html

Extract mysql_connector jar file into three folders in the classes folder.
Like this : com folder, META-INF folder, and org folder.

Related

How to get some data from a restful web service, and save it to the database?

I have written some code to save some data into database by restful web services, utilizing SOAPUI as user interface. I use #put to do that. Here is the steps of running:
1- run the code on Tomcat 9.0 server.
2- use the URL in SOAPUI to PUT some data.
But when I use PUT in SOAPUI, give the string values of first and last, and run it, the values are not added to my database. Hoewer, the json file got the right values
{
"first": "Jon",
"last": "Snow"
}
Here is the important pieces of my code:
package tomcat.rest.eclipse.database;
public class Score {
public static String first, last;
}
public class ScoreService {
#PUT
#Path("/score")
#Produces("application/json")
public String update(#QueryParam("first") String first,
#QueryParam("last") String last) {
Score.first = first;
Score.last = last;
final String var1 = Score.first;
final String var2 = Score.last;
database.insert(var1, var2);
String pattern = "{ \"first\":\"%s\", \"last\":\"%s\"}";
return String.format(pattern, Score.first, Score.last);
}
}
And this is my connection :
public class database {
public static Connection getConnection() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "00000";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected");
return conn;
} catch(Exception e) {System.out.println(e);}
return null;
}
public static void insert(final String var1, final String var2) {
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO student (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch(Exception e) {System.out.println(e);}
finally {
System.out.println("Insert completed");
}
}
}
The output on console is:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
Insert completed
How can I connect the web service to database properly to save some records in database? Thank you so much for helping me.
Just download and add the mysql connector jar to your project build path.
Or
Add the jar file to your WEB-INF/lib folder. Right-click your project
in Eclipse, and go to "Build Path > Configure Build Path" Add the "Web
App Libraries" library This will ensure all WEB-INF/lib jars are
included on the classpath.
Or the jdbc mysql maven dependency if you use maven :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
Edit: right click on your project => Build Path => Configure Build
Path => tab "Libraries" and you click on "Add External JARs" and you
point to your file "mysql-connector-java-5.1.17-bin.jar"
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.EmptyStackException;
public class SingletonConnection {
private static Connection connection = null ;
static
{
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/dbnameX","root","");
}catch(Exception ex)
{
}
}
public static Connection getConnection() throws Exception {
return connection;
}
}

SQL Server conecction with jdbc eclipse

I have the following code to connect to my database in SQL Server:
public static void main (String [] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://DESKTOP-G8057U8\\SQLEXPRESS:1433;databaseName=Vaporizadores;integratedSecurity=true;";
DBConection=DriverManager.getConnection(url);
DBStatement = DBConection.createStatement();
System.out.println("Conexion exitosa");
}catch(ClassNotFoundException | SQLException e) {
System.out.println("Conexion fallida");
}
}
when I run it I get "Conexion fallida", meaning that an exception was catched. I've tried different urls but I still can't connect to my DB. I know very little about jdbc and sql server, so it may be a stupid error.
It worked like this:
String url = "jdbc:sqlserver://DESKTOP-G8057U8;databaseName=Vaporizadores;integratedSecurity=true;";
and i added the sqljdbc_auth.dll to Java bin folder

jdbc mysql driver not found after deploying

I have developed a REST application using jersey where to connect to database(mysql) I use jdbc connection. Following is the configuration.
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/DBNAME";
static final String USER = "root";
static final String PASS = "********";
public List<Item> getAll() {
List<Item> results = new ArrayList<>();
try (Connection conn = (Connection) DriverManager.getConnection(DB_URL,
USER, PASS);
Statement stmt = (Statement) conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM items");) {
while (rs.next()) {
// Retrieve by column name
System.out.println(rs.getInt("ID"));
System.out.println(rs.getString("FormerCode"));
System.out.println(rs.getString("NewCode"));
results.add(new Item(rs.getInt("ID"), rs
.getString("FormerCode"), rs.getString("NewCode")));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return results;
}
All things works when I deploy via Eclipse. But when I create the war file and deploy it manually on tomcat server it gets the exception saying there is no suitable driver.
No suitable driver found for 'jdbc:mysql://localhost:3306/DBNAME
I have included the mysql-connector jar files in both WEB-INF/lib folder and TOMCAT_HOME/lib folder. But I am still getting this error. Server is running on Ubuntu Server 14.04.
Paths where jar is added.
src/main/webapp/WEB-INF/lib
usr/share/tomcat7/lib
What seems to be the problem hence I have added the jar files to necessary locations??
Sometimes java class failed to pick driver's(mysql java connector jar file) path from lib folder. To remove this issue you can extract connector jar in following directory of your project.
src/main/webapp/WEB-INF/classes
OR
You may also compile the java file with classpath reference of mysql_java_connector.jar.
The answer was when using a DriverManager interface to create a JDBC Connection, always create an instance of your JDBC driver first in order to load it into your Classloader.
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (Exception ex) {
// handle the error
}
Thanks all.

JDBC not connecting

While the build paths are not correct I obtain “com.microsoft.sqlserver.jdbc.SQLServerDriver” from the stack trace. As they are built correctly, I obtain my printed statement “Successfully connected”. The JDBC is living within the getter/setters of the webservice as a method.
When I place the JDBC content in its own file with no builds and run as a java application I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
When I place the JDBC content in its own file with builds and run as a java application I receive: “Successfully connected”
When the method is called from a test file as a java application I receive: “Successfully connected”
Ex:
public static void main(String[] args) {
insert.main(args);
When the method is run as a java application on PO I receive: “Successfully connected”
When I place the method to be called under a setter (which will be invoked by the client, which will cause the jdbc to be invoked) I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Would you happen to have any tips for me? I’m clueless why it will work under being invoked as an application but not via client?
public class insert{
public static void main(String[] args) {
Connection con = null;
Statement st = null;
final String DB_URL = "jdbc:jtds:sqlserver://00.00.00.00:0000/DB";
// Database credentials
final String USER = "usrname";
final String PASS = "pw";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
st = con.createStatement();
System.out.println("successfully connected!");
} catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
finally {
try {
con.close();
} catch (Exception e) { /* ignored */ }
try {
st.close();
} catch (Exception e) {
/* ignored */
}
}
}
}
Any tips at this point would be greatly appreciated.
The problem is that your jar misses the necessary libraries that provides com.microsoft.sqlserver.jdbc.SQLServerDriver class and others to communicate with your SQL server. You have to make sure the library is loaded and available when is being executed from tomcat. Just copy your library and drop it inside %TOMCAT_INSTALL%/lib folder, where %TOMCAT_INSTALL% is the folder where your tomcat is installed, so the library will be available for every project (war, jar, etc) that runs in your tomcat installation.

Connecting to Derby using JDBC

I am trying to connect to Derby database on my locahost using JDBC.
I have started the database using the command: java -jar lib;derbyrun.jar server start, which starts successfully on port 1527.
On another command terminal, I use the command: java -classpath .;lib;derbyclient.jar testsqldatabase.TestSQLDatabase but I get the error below:
java.sql.SQLException: No suitable driver found for jdbc:postgresql:COREJAVA
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at testsqldatabase.TestSQLDatabase.getConnection(TestSQLDatabase.jav
)
at testsqldatabase.TestSQLDatabase.runTest(TestSQLDatabase.java:39)
at testsqldatabase.TestSQLDatabase.main(TestSQLDatabase.java:26)
My datatbase.properties file contains the following lines:
jdbc.drivers=org.postgresql.Driver
jdbc.url=jdbc:postgresql:COREJAVA
jdbc.username=dbuser
jdbc.password=secret
The java program is is listed below:
public class TestSQLDatabase
{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
try
{
runTest();
}
catch(SQLException ex)
{
for(Throwable t: ex)
t.printStackTrace();
}
}
/*Runs a test by creating a table, adding a value,
showing the table contents, removing the table*/
public static void runTest() throws SQLException, IOException
{
try(Connection conn = getConnection())
{
Statement stat = conn.createStatement();
stat.executeUpdate("CTEATE TABLE Greetings (Message CHAR(20))");
stat.executeUpdate("INSERT INTO Greetings VALUES ('Hello, World!')");
try(ResultSet result = stat.executeQuery("SELECT * FROM Greetings"))
{
if(result.next())
System.out.println(result.getString(1));
}
stat.executeUpdate("DROP TABLE Greetings");
}
}
/*
* Gets a connection from the properties specified in the
* file database.properties. #return the database connection
*/
public static Connection getConnection() throws SQLException, IOException
{
Properties props = new Properties();
try(InputStream in = Files.newInputStream(Paths.get("database.properties")))
{
props.load(in);
}
String drivers = props.getProperty("jdbc.drivers");
if(drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username, password);
}
}
Can anyone figure out why I am getting that error from the second command terminal?
Thanks, much appreciated
Derby is a database. PostgreSQL is a different database. You're running a Derby database and you need the corresponding Derby JDBC driver to talk to it - not the PostgreSQL one.
You want to connect to Derby by using the PostgreSQL driver (in the properties file); also the URL of the database is no written well; it should be: jdbc:${dataBaseVendor}:${server}:${port}/${databaseName} where in your case databaseVendor=derby.
And also make sure you have the Derby JDBC driver jar on your classpath.

Categories