MySql Driver Not Loading In Java - java

When I use the following line,
Class.forName("com.mysql.jdbc.Driver");
//Sets up database connection
connect = DriverManager.getConnection("jdbc:mysql://www.papademas.net/tickets?"
+ "user=root&password=jamesp");
statement = connect.createStatement();
String sql = "INSERT INTO JReimTicketer (dateIssued, ticketName, issuerName,"
+ " issuerDepartment, ticketDescription, activity) "
+ "VALUES (SYSDATE(),'"+ticketName+"', '"+issuerName+"', "
+ "'"+issuerDepartment+"', '"+ticketDescription+"', "
+ " '"+activity+"')";
my program stops, and it doesn't seem like it loads the driver. I've downloaded it, so I'm not sure why it's not working. Any help would be appreciated.

Firstly if your are using jdbc 4.0, you don't require
Class.forName("com.mysql.jdbc.Driver");
to load driver as it it auto-loaded when you call
DriverManager.getConnection();
If you have specified mysql jar in your class path, the problem must be in your url. So kindly check your URL/Username/Password
Also, if you are getting exception,please post stacktrace

Your code seems to be correct. And I think you're right. Things aren't missing from Front-End but Back-End. So, before you compile your code, you need to put MySQL Connecter jar (mysql-connector-java-x.x.xxx-bin.jar) file in your Java Buildpath Path. Do it before you compile and run the code.

Related

Java, sqlite3 since command line troubleshooting

my name is Omar
i am following the instructions in this webpage https://www.tutorialspoint.com/sqlite/sqlite_java.htm in order to compile a sample program of java conected with sqlite3.
sample program
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
try {
// Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
i downloaded the sqlite connector sqlite-jdbc-3.7.2.jar but according to the webpage above, i Added the address of downloaded jar file sqlite-jdbc-(VERSION).jar in my class path(the same class path of mysql address connector) and place the sqlite-jdbc-3.7.2.jar in C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext just like mysql connector driver.
but i got bad results when i try to run it in command line
"No suitable driver found for jdbc: sqlite: test.db"
i run java -classpath ".;sqlite-jdbc-3.7.2.jar" SQLiteJDBC with the sqlite-jdbc-3.7.2.jar in the same folder in command line but i got bad results too.
"No suitable driver found for jdbc: sqlite: test.db"
Where sqlite-jdbc-3.7.2.jar connector should be placed according to connect java and sqlite just as myql do?
anyhelp is appreciated
thank you in advance
Omar
You should download and use the newest SQLite driver 3.27.2.1 from this site: https://bitbucket.org/xerial/sqlite-jdbc/downloads/
I tried it with 3.7.2 and got the same error. But with 3.27.2.1 it works well.

OpenShift 3: How To Access POSTGRESQL POD Environment Variables Using Java?

I have a Java webapp running successfully on Tomcat.
I have created three environment variables in my myapp deployment:
MY_ENV_VAR_1=dbuser
MY_ENV_VAR_2=dbpassword
MY_ENV_VAR_3=dbname
I can get these values using standard Java code:
myEnvVar1 = System.getenv("MY_ENV_VAR_1");
myEnvVar2 = System.getenv("MY_ENV_VAR_2");
myEnvVar3 = System.getenv("MY_ENV_VAR_3");
I used 'normal Java' code to connect to the database:
connection = DriverManager.getConnection("jdbc:postgresql://" + postgresqlServiceHost + ":" + postgresqlServicePort + "/" + myEnvVar3, myEnvVar1, myEnvVar2);
So, I can connect to the database successfully.
The problem is:
I can see (in web console) but cannot get the values from the three environment variables in the postgresql deployment:
POSTGRESQL_USER
POSTGRESQL_PASSWORD
POSTGRESQL_DATABASE
Using the 'normal' System.getenv("POSTGRESQL_USER"); does NOT work.
So, please can someone tell me how to access the values of these three postgresql pod environment variables using Java Code?
So, the simple answer is:
You manually add the following three environment variables to the deployment environment of the application that will be accessing the database.
POSTGRESQL_USER
POSTGRESQL_PASSWORD
POSTGRESQL_DATABASE
You must do it in exactly the same way as you see them in the postgresql deployment environment.
It really is that simple...
In Java app:
String postgresqlServiceHost = System.getenv("POSTGRESQL_SERVICE_HOST");
String postgresqlServicePort = System.getenv("POSTGRESQL_SERVICE_PORT");
String postgresqlDatabase = System.getenv("POSTGRESQL_DATABASE");
String postgresqlUser = System.getenv("POSTGRESQL_USER");
String postgresqlPassword = System.getenv("POSTGRESQL_PASSWORD");
Connection connection = DriverManager.getConnection("jdbc:postgresql://" + postgresqlServiceHost + ":" + postgresqlServicePort + "/" + postgresqlDatabase, postgresqlUser, postgresqlPassword);

Java JDBC JTDS test connection string

I have an application using JTDS to connect to SQL Server. I need to change the database and want to test the connection string first before reconfiguring the application. I'm a SQL Server DBA, not a Java developer!
Here's my test code:
// Import the SQL Server JDBC Driver classes
import java.sql.*;
class Example
{
public static void main(String args[])
{
try
{
// Build the connection string, and get a connection
System.out.println("1.");
System.out.println("2.");
String connectionUrl = "jdbc:jtds:sqlserver://UK-SB-Server:53569;DatabaseName=helpdesk;user=helpdesk;password=MyPwd;Tds=8.0;PrepareSql=3;XaEmulation=false";
System.out.println("3.");
Connection con = DriverManager.getConnection(connectionUrl);
System.out.println("Connected.");
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT * from dbo.AllowedValues";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next())
{
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
}
catch(Exception e)
{
System.out.println("Error - " + e.getMessage());
System.exit(0);
}
}
}
I compile it with:
C:\Progra~1\Java\jdk1.6.0_45\bin\javac C:\JavaTest\example.java
I run it with:
C:\Progra~1\Java\jdk1.6.0_45\bin\java -classpath C:\JavaTest Example
jtds-1.2.jar and Example.class are both in C:\JavaTest
I get the following error:
1.
2.
3.
Error - No suitable driver found for jdbc:jtds:sqlserver://UK-SB-Server:53569;DatabaseName=helpdesk;user=helpdesk;password=MyPwd;Tds=8.0;PrepareSql=3;XaEmulation=false
I've read conflicting posts as to whether I need
Class.forName("net.sourceforge.jtds.jdbc.Driver");
or not. If I put the line between println("1.") and println("2."), it just fails earlier with
1.
Error - net.sourceforge.jtds.jdbc.Driver
I may be missing something obvious, but please help me resolve this issue.
You appear to be facing two issues:
Issue 1. It seems that jTDS 1.2 is sufficiently old that you actually do need to call
Class.forName("net.sourceforge.jtds.jdbc.Driver");
before you try to establish the connection.
Issue 2. When you specify the classpath, you need to explicitly include the jTDS jar file. That is, this won't work ...
C:\JavaTest>"\Program Files\Java\jdk1.6.0_45\bin\java.exe" -cp C:/JavaTest Example
1.
Error - net.sourceforge.jtds.jdbc.Driver
... but this works for me:
C:\JavaTest>"\Program Files\Java\jdk1.6.0_45\bin\java.exe" -cp C:/JavaTest;C:/JavaTest/jtds-1.2.jar Example
1.
2.
3.
Connected.
...
Lets break down steps, run following commands from cmd:
cd C:\JavaTest
set path=C:\Progra~1\Java\jdk1.6.0_45\bin
javac example.java
java -cp .;jtds-1.2.jar -Djdbc.drivers=net.sourceforge.jtds.jdbc.Driver Example
The last line will load the driver manually, so no need to change code.
Problem is that you need to register driver before making connections to database.
I've read conflicting posts as to whether I need
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Yes, but you have to place it before line
Connection con = DriverManager.getConnection(connectionUrl);

No suitable driver found for jdbc:db2: in java

I'm trying to connect to a remote database using the following java code, but I get an error saying no suitable driver found
I have included the required db2 libraries in my project:
I have declared the jdbc settings in the main class
Settings.loadSettings();
Class.forName("Settings.DB2_JDBC_DRIVER");
Controller con = new Controller();
con.business_logic();
}
Then trying to connect the database in another class
public Connection getDBConnection()
{
Connection DBConnection = null;
try {
System.out.println("Connecting to database " + Settings.DBName + ".");
String DBURL = "jdbc:db2://" + Settings.DBServer + ":" + Settings.DBPort +
"/" + Settings.DBName + ";";
String decryptedPass = decryptPassString(Settings.DBPass);
DBConnection = DriverManager.getConnection(DBURL, Settings.DBUser,
decryptedPass);
System.out.println("Database connection successfully established to
database " + Settings.DBName + " using user " + Settings.DBUser + ".");
return DBConnection;
}
catch (Exception e) {
System.out.println("An unexpected error occurred when attempting to
establish connection to database " + Settings.DBName + ". The error was: "
+ e.getMessage() + "\r\n" + e.getMessage()); }
return DBConnection;
}
can anyone please explain what i am missing here ?
The error message i am receiving is
An unexpected error occurred when attempting to establish connection to database DWHER00. The error was: No suitable driver found for jdbc:db2:/
The line:
Class.forName("Settings.DB2_JDBC_DRIVER");
should ideally be something like this:
Class.forName("com.ibm.db2.jcc.DB2Driver");
unless you are creating your own driver for DB2.
You will need the JAR files for the DB2 installation that you are using.
Put them in the class path and make the above code change. And it should work.
IBM DB2 Universal Driver Type 4
Driver Class Name:
com.ibm.db2.jcc.DB2Driver
Driver Jar Files: db2jcc.jar and db2jcc_license_cu.jar
(Both of these jars must be included)
JDBC URL Format:
jdbc:db2://<host>[:<port>]/<database_name>
JDBC URL Examples:
jdbc:db2://127.0.0.1:50000/SAMPLE
IBM DB2 Universal Driver Type 2
Driver Class Name:
com.ibm.db2.jcc.DB2Driver
Driver Jar Files: db2jcc.jar and db2jcc_license_cu.jar
(Both of these jars must be included)
JDBC URL Format:
jdbc:db2:<database_name>
JDBC URL Examples:
jdbc:db2:sample
Hope this helps!
Make sure the /lib folder is added to the build path of your project as well. See here other answer

Connecting to Netbeans SQL Database for the first time - java.sql.SQLException: No suitable driver found 0 08001

I am fairly new to Java, so I bought a book to learn from. Everything went swimmingly until I got to the chapter on SQL. I am working in NetBeans with the sample database, but I can't get the database to connect with the program.
Here's the code I faithfully copied from the book:
import java.sql.*;
public class SysTableReporter {
public static void main(String[] arguments) {
String data = "jdbc:derby://localhost:1527/sample";
try (
Connection conn = DriverManager.getConnection(
data, "app", "APP");
Statement st = conn.createStatement()) {
System.out.println("TABLEID:\t" );
Class.forName("org.apache.derby.jdbc.ClientDriver");
ResultSet rec = st.executeQuery(
"select * " +
"from SYS.SYSTABLES " +
"order by TABLENAME");
while(rec.next()) {
System.out.println("TABLEID:\t" + rec.getString(1));
System.out.println("TABLENAME:\t" + rec.getString(2));
System.out.println("TABLETYPE:\t" + rec.getString(3));
System.out.println("SCHEMAID:\t" + rec.getString(4));
System.out.println();
}
st.close();
} catch (SQLException s) {
System.out.println("SQL Error: " + s.toString() + " "
+ s.getErrorCode() + " " + s.getSQLState());
} catch (Exception e) {
System.out.println("Error: " + e.toString() + e.getMessage());
}
}
}
Here's what my Services Panel looks like:
Click to view Image
Here's my output:
SQL Error: java.sql.SQLException: No suitable driver found for jdbc:derby://localhost:1527/sample 0 08001
At first I figured I just had some typo, but looking over it carefully I can't find it. I tried installing a new JDBC driver, but that didn't seem to help either. I'm running a Windows 8 laptop, and I have the telnet client turned on. My best guess at this point is that I somehow missed a step in the initial setup, but I can't find it to go back and fix it. Any help would be great.
You are probably just missing the Derby JDBC driver jar in your project's library section (I'm assuming that you created a standard Netbeans project, not a Maven type project). The jar is called derbyclient.jar.
The easiest way to solve this:
locate derbyclient.jar eg with Explorer
in Netbeans, rightclick on the project node in the Projects pane.
Select Properties, and there select libraries
Click "Add JAR/Folder", navigate to derbyclient.jar
That effectively adds the jar to your project. Just recompile, run and everything should work as intended.
EDIT: aside from #BobKuhar's find, another problem with the given code is that it doesn't use one of Java's more powerful debugging mechanisms, the stacktrace. At its most basic form, showing them on screen is simple, not more than
} catch (SQLException s) {
System.out.println("SQL Error: " + s.toString() + " "
+ s.getErrorCode() + " " + s.getSQLState());
// and show us the stacktrace
s.printStackTrace();
} catch (Exception e) {
System.out.println("Error: " + e.toString() + e.getMessage());
// and show us the stacktrace
e.printStackTrace();
}
the stack trace will not only show you the exact line at which the error occurred, but also the trajectory to the exception (how the program got there), invaluable in more complicated programs. Definitely something you want to learn to use!
Lots of info on stack traces here: What is a stack trace, and how can I use it to debug my application errors?
I think what you really have is just a sequencing problem. The Class.forName call registers the driver with the DriverManager (I think). This needs to occur before you attempt to establish a Connection through the DriverManager.
Class.forName( "org.apache.derby.jdbc.ClientDriver" ).newInstance();
Connection conn = DriverManager.getConnection( data, "app", "APP");
If this gives you some "ClassNotFound" exception, then fvu's assertion that you don't have the Derby JDBC Jar on the class path is your next issue.
The Derby docs have an example: http://db.apache.org/derby/integrate/plugin_help/derby_app.html

Categories