Get mysql and java to work together - java

I have Eclipse Indigo on Mac Os X and I have downloaded mysql connector (version 5.1).
I have added the jar to the project and I am using this code:
public class Test
{
public static void main (String[] args)
{
try {
String url = "jdbc:msql://200.210.220.1:1114/Demo";
Connection conn = DriverManager.getConnection(url,"","");
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT Lname FROM Customers WHERE Snum = 2001");
while ( rs.next() ) {
String lastName = rs.getString("Lname");
System.out.println(lastName);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
When I try to execute the program I get this exception:
Got an exception!
No suitable driver found for jdbc:msql://200.210.220.1:1114/Demo
My question is : how to install the driver? What else should I do?
And once installed the driver, how do I get my database URL (I am using mysql 5.5)?
I haven't found a valid guide on the web, they're all too specific.

Your JDBC connection URL is not correct, refer to the official documentation to check the required format for the URL .
In your case the URL will become :
String url = "jdbc:mysql://200.210.220.1:1114/Demo";

you're missing the "y" in jdbc:mysql

You are using MySQL, the URL should look like this:
jdbc:mysql://200.210.220.1:1114/Demo
may be, review the IP and PORT.

You may have added the jar to your project but have you also added it to the project classpath? Having the jar exist as a file in your project won't solve the problem. The jar file is clearly not accessible to your program. Right click on your project -> Build Path -> add the jar there.
Database URL looks ok, assuming you have the right host address and port number.

Related

How to fix java.sql.SQLException. No suitable driver for jdbc [duplicate]

This question already has answers here:
Getting the following error - No suitable driver found for jdbc:postgresql://localhost: 5432/testDBMS
(4 answers)
Closed 3 years ago.
I'm getting an error java.sql.SQLException No suitable driver for jdbc:derby:books when I try to run a file from command line. In Eclipse, everything works fine. I read a book "Java, How To Program" Deitel&Deitel and the file is an example from it. When I try to compile program from command line it shows no error, but the problem is with running. Please help
public class DisplayAuthors {
public static void main(String args[]) {
final String DATABASE_URL = "jdbc:derby:books";
final String SELECT_QUERY =
"SELECT authorID, firstName, lastName FROM authors";
String user="deitel";
String password="deitel";
try (
Connection connection = DriverManager.getConnection(
DATABASE_URL, user,password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(SELECT_QUERY)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
System.out.printf("Table Authors database books:%n%n");
for (int i = 1; i <= numberOfColumns; i++) {
System.out.printf("%-8s\t", metaData.getColumnName(i));
}
System.out.println();
while (resultSet.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
System.out.printf("%-8s\t", resultSet.getObject(i));
}
System.out.println();
}
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}
Command line execution:
javac DisplayAuthors.java
java DisplayAuthors
You are running in the command line your class file without the dependencies.
In your eclipse IDE you maybe have a derby.jar or similar dependencies and eclipse adds all automatically to the execution. Is required to add all the dependencies when you are executing directly from the command line.
If you are note creating a runnable jar with dependencies in MANIFEST.MF and you are trying to execute the class directly is required to add the -cp parameter with the path to all the dependencies:
Example:
java -cp Derby.jar;. DisplayAuthors
Summing that the Derby.jar and your class are in the same place and there is no more dependencies to add.
More information about:
Java Command line (Oracle Java9 SE)
Differences between "java -cp" and "java -jar"?
java.sql.SQLException. No suitable driver for jdbc
The above error jumps when JDBC DriverManager can't find any suitable driver for the given connection URL. Either the JDBC driver isn't loaded at all before connecting the DB, or the connection URL is wrong.
The URL should be like this,
jdbc:derby://localhost:1527/dbname;create=true;
or
jdbc:derby:books;create=true;
Use create=true if you want the database to be created if it doesn't exist.
And finally, check that Derby JAR file is on the classpath. If you can't find it, then you can download the JAR from here and add to the project Library folder.
For Apache Derby, the driver class name is org.apache.derby.jdbc.ClientDriver. So put that as follows,
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection connection = DriverManager.getConnection(DATABASE_URL, user, password);
Make sure your URL, username and the password is correct, and try to run your code.

Unable to add odbc5.jar in classpath

I want to connect to the oracle DB using Play Framework 1.2.5. FOr this I have modified the application.conf file as follows:
db.url=jdbc:oracle:thin:#localhost:1521/orcl
db.driver=oracle.jdbc.OracleDriver
db.user=system
db.pass=tiger
Then I tried to add the driver i.e. classes12.jar/odbc5.jar but everytime when i try to run it, I am getting the exception:
Cannot connect to the database, Driver not found
For adding the jar file in Eclipse IDE, below are the steps I tried:
1) Added it in the lib folder (present under the root directory of my new application) and then added it to the java build path
2) Added it in the framework/lib folder (inside the downloaded framework folder) and then added it to the java build path
In both the cases, I am getting the above mentioned exception.
Also, Please list down the steps for connection to an oracle db, I am not able to find it anywhere in the documentation
EDIT
I am able to add the jar in the classpath, everything was fine except that I did not restarted the server once it failed to connect the jar.
I did this code for fetching some data from the database:
Connection conn = DB.getConnection();
PreparedStatement stmt = null;
System.out.println(conn);
try {
stmt = conn.prepareStatement("select dept_id from emp where emp_id = 11");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
System.out.println("Dept Id: " + rs.getInt("dept_id"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This approach is working but I am having a confusion:
If I comment the entire block of code and run the application then I can see the message in the console stating the connection is made to the DB. Hence :
1) Is the above block of code the right approach to fetch the data from Oracle DB or something better than this is present?
2) Is it like for the entire application lifetime, the connection with tht DB will persist?
I am a newbie in this, hence struggling :(
Please let me know hoe to proceed with this.
Regards
Oracle db driver class name is oracle.jdbc.driver.OracleDriver

Java SQL error, no suitable driver found

I'm trying to compile this small piece of code, to help me connect to my db and retrieve some information to test it. I am using Netbeans on a Windows 7 x64 machine. This is the code:
package passwordprotector;
import java.sql.*;
public class PasswordProtector {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String host = "jdbc:derby://localhost:1527/PasswordProtector DB";
String dbUsername = "john";
String dbPassword = "arsenal";
/*try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
}catch(ClassNotFoundException e){
System.out.println(e);
}*/
try{
Connection con = DriverManager.getConnection(host, dbUsername, dbPassword);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM APP.PERSON");
while (rs.next()) {
String uName = rs.getString("uname");
String uPass = rs.getString("upass");
System.out.println("Username: " + uName + "/n" + "Password: " + uPass);
}
}catch(SQLException e){
System.err.println(e);
}
}
}
When I compile and run I receive this error:
java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/PasswordProtector DB
BUILD SUCCESSFUL (total time: 0 seconds)
When I right click on my db and select properties I can see it's location, like so:
Database URL: jdbc:derby://localhost:1527/PasswordProtector
I've checked with others who have posted about this and it seems they had an incorrect URL as the issue, but I can't see any other URL which I can use apart from the one posted.
I've tried with and without the ending ' DB' for the String host, neither works.
I've also already read from here and still couldn't figure out why the URl is incorrect:
Not sure the problem with the database URL connection, but in the usage of the correct driver. If the database is embedded you should use the driver commented in your post and example from my answer, there's also tutorial embedded derby.
if not then use
Class.forName("org.apache.derby.jdbc.ClientDriver");
It's a different driver to connect to the database running standalone. In this case see derby network client documentation how to configure and run derby network client.
Make sure derbyrun.jar is in your classpath. It resides in the db/lib directory of your JDK.
Doing a quick search on Maven and Derby, included the following in my pom:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.10.2.0</version>
</dependency>
and everything worked afterwards, so it may be a library reference issue if the previous solution did not work.

Getting Error when connection to MySQL database

I have downloaded the following:
mysql-essential-5.1.65-win32 from this MySQL Dev link
MySQL Connector mysql-connector-java-5.1.21.zip from this link
Now I have started programming with Eclipse. I have made simple java class like below,
public class MySQLAccess {
private static Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main(String[] args){
try{
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
}catch (Exception e) {
// TODO: handle exception
System.out.println("Error : "+e);
}
}
}
I have also made a folder "lib" in my Java project and I have put that mysql-connector jar over there. But when I run this program it can't find mysql I get the following error in the console :
Erro : java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Can someone please tell me where I have made the mistake? Thank you
Putting the full jar-file path in your classpath and restarting cmd (if you are running from cmd) should work-
See here- java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
If it your java application project then you put jar file into jdk library path ext folder.
eg:
C:\Program Files\Java\jdk1.6.0_13\jre\lib\ext
you will get path from your project class path .

Jar file won't recognize mysql database

I made a swing application in Eclipse and it works and compiles fine in Eclipse. It's connecting to mysql. The problem is when I turned it into a jar file the database won't connect. When the application is supposed to load the information from the db, nothing is happening.
public boolean deleteAttendance(String idno,String eventtitle)
{
int x;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(dbUrl, "","");
String query = "DELETE FROM attendance WHERE id =? AND title = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, idno);
pstmt.setString(2, eventtitle);
x = pstmt.executeUpdate();
if(x != 0)
return true;
else
return false;
}catch(Exception e)
{
System.out.println("Statement Error " + e);
}
return false;
}
Just to check whether it is the problem with your required jars not on the class path
Go to window -> preferences->java->build path->user Libraries. add your jar to new user library. Now create a new java project in eclipse right click on this project and select add libraries and add the library your just added in your eclipse . Also add required libraries for database (if any) to your project. If on running your jar everything is working fine then surely its the problem of you not adding ODBC/JDBC driver to your class path else its a problem with your jar .
You would need to make sure that the ODBC driver is in your classpath.
Eclipse does a good job of making sure that your driver is there (because you have to include your dependency jars or else get errors trying to use them).
But once you leave Eclipse - you have to do it yourself.
Is it in your classpath?
To fix this problem, go to artifact and add ojdbc.jar and click OK.
If true then nothing, if not then re-create the jar file.
note:Just make sure ojdbc.jar is added.

Categories

Resources