Java JDBC JTDS test connection string - java

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);

Related

Unable to load suitable drive from java 18 on linux 24.02.1 wsl with mysql version 8.0.31 [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
What is a classpath and how do I set it?
(10 answers)
Closed last month.
I get the following error when trying to execute a Java program with SQL code:
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost/opiejbc1
I have installed the driver mysql-connector-j-8.0.31.jar in /usr/share/java
I have called the class with java -cp ./:/usr/share/java TestApplication
and with CLASSPATH=./:/usr/share/java set.
My Java code is as follows:
import java.sql.*;
public class TestApplication {
static final String DB_URL = "jdbc:mysql://localhost/opiejbc1";
static final String USER = "opiejbc1";
static final String QUERY = "SELECT * FROM Test1";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, "");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
// Extract data from result set
while (rs.next()) {
// Retrieve by column name
System.out.print("Name: " + rs.getInt("Name"));
System.out.print(", Phone: " + rs.getInt("Phone"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I have tried inserting Class.forName("com.mysql.cj.jdbc.Driver"); immediately after the try statement, but then I get the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token(s), misplaced construct(s)
at TestApplication.main(TestApplication.java:10)
What am I doing wrong?
I have tried all the recommended solutions as far as I know, but I still get those errors.
As noted by #g00se, the real problem is that the JAR file for the Connector/J driver is not on your runtime classpath. So the java runtime cannot find it.
Solution: put the JAR file on the classpath.
Notes:
If you use a -cp option, the CLASSPATH environment variable is ignored.
If you put a directory on the classpath, you are NOT telling the java to put JAR files (in that directory) on the classpath.
If you wanted to put all JAR files in (say) "/usr/share/java" on the classpath, you could use a wildcard entry; e.g. -cp .:/usr/share/java/*.jar. Note that the *.jar is not shell globbing. It needs to be processed by the java command. (In some cases you may need to escape it to prevent globbing.)
You should (IMO) take the time to read the Oracle documentation on how the classpath works.
Adding a Class.forName call is NOT recommended (except by people who don't understand the problem). If the drivers are on the classpath then DriverManager will find them. And if they are not on the classpath, then using Class.forName is going to fail.
But the reason that you got a compilation error was that you were inserting it at the wrong place:
try ( // HERE is the wrong place
Connection conn = DriverManager.getConnection(DB_URL, USER, "");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(QUERY);) {
The try with resources syntax only allows variable declarations with initializers in that context. A Class.forName call is not such a thing.
I haven't checked, but I think that inserting
Class dummy = Class.forName("com.mysql.cj.jdbc.Driver");
at // HERE in the above would make the compiler happier. But DON'T. It is unnecessary. It won't help. See above for the correct solution.

How to establish connection between Java Program and Database without using IDE/ External Tools?

I want to write a Java Program for Establishing Connection between Java Program and Database, but I don't want to use any IDE like Netbeans, Eclipse, Visual Studio, XAMP, etc. I have jar files for Driver of required DBMS.
public class JDBCDemo
{
public static void main(String args[])
{
try
{
/**
* Steps for Establishing Connection between Java Application and Database
*/
//1. Load and Reginster Driver
Class.forName("com.mysql.jdbc.Driver");
//2. Establish a connection between Java Application and Database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicals", "root", "root123");
//3. Create Statement Object
Statement st = con.createStatement();
//4. Send and Execute SQL queries
ResultSet rs = st.executeQuery("SELECT * FROM tushar");
//5. Process the result from ResultSet object
while(rs.next())
{
System.out.println(rs.getString(1));
}
//6. Close the Connection
con.close();
}
catch(Exception e)
{
System.out.println(e.toString().trim());
}
}
}
It is showing error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
How to Establish connection ??
You need to add the mysql driver jar in the classpath before you run the program.
There are various ways to do so.
javac -cp "JAR_PATH" ClassName.java
java -cp "JAR_PATH" ClassName
Add the jar file in C:\Program Files\Java\\jre\lib\ext
set classpath=PATH_TO_JAR;
colon(:) is compulsory after jar file name
Compilling Program
javac -cp mysql-connector.jar: ProgramFileName.java
javac -cp mysql-connector.jar: JDBCDemo.java
Running Program
java -cp mysql-connector.jar: ProgramFileName
java -cp mysql-connector.jar: JDBCDemo
Note:- Simillar can be applied while using other jar files for performing other operations.
Sample Output

JDBC no suitable driver found just on Linux? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
I am trying to write a program to connect to a MySQL database in eclipse, but I get the error "java.sql.SQLException: No suitable driver found".
The java code is:
import java.sql.*;
public class FirstExample {
//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";
public static void main(String[] args) {
try {
System.out.println("Connecting to database...");
//Class.forName(S_JDBC_DRIVER);
Connection connection = DriverManager.getConnection(S_DB_URL,
S_USER, S_PASS);
System.out.println("Creating statement...");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int iId = resultSet.getInt("id");
int iAge = resultSet.getInt("age");
String sFirst = resultSet.getString("fname");
String sLast = resultSet.getString("lname");
System.out.print("ID: " + iId);
System.out.print("\tAge: " + iAge);
System.out.print("\tFirst: " + sFirst);
System.out.println("\tLast: " + sLast);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
for (Throwable t : se) {
t.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
The output in the console tab is:
Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
I have used the MySQL Connector/J. It is unzipped in the MySQL installation directory and the jar file is added to the CLASSPATH.
Also refer to this image. There is an ! mark at the project root.image01
I get the error as in the next image: image02 when I include the 2 commented statements:
static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
For all but the most trivial applications the CLASSPATH environment variable is NOT used. Normally the libraries are include in the Class-Path entry in the manifest of the jar, or in the -cp option of the java commandline.
In this case you need to add the MySQL JDBC driver to the buildpath of your Eclipse project.
I had the same problem. I solved it by adding:
Class.forName("com.mysql.jdbc.Driver");
you can place the path like java -cppwd/mysql-connector-java-5.1.22-bin.jar:. <classname>.
make sure that your in same directory where the mysql driver is .
Hope that helps .
Load Driver class just before getting the connection.
Use this code:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "user", "passw");
Alternatively you can also add the installed jar file to your eclipse project by selecting the project in eclipse, right click it and go down to properties, select the Java Build Path>>select the Libraries Tab>>Add external jar file and browse for the installed mysql-connector-java.jar file or any mysql java connector file int the /usr/share/java/ directory for most ubuntu users. Click okay and rebuild your project. Good luck
I encountered the same problem as you, but I handled it as follows:
I copied the jar, which is called mysql-connector-java-5.1.23-bin.jar, into the \Apache Software Foundation\Tomcat 6.0\lib, and restarted tomcat.
Hope that helps

Why is java.sql.DriverManager.getConnection() still working after removing the SQLite database JAR?

I'm having difficulties in Java with an SQLITE database provided in a separate JAR file.
Surprisingly, the sqlite database seems to be accessed even after removing the JAR file, exiting and restarting the program and even after rebooting the machine.
I'm using the Xerial driver sqlite-jdbc-3.7.2.jar (for org.sqlite.JDBC).
EDIT: very same issue with sqlite-jdbc-3.8.6.jar.
Xerial JDBC driver is published here:
https://bitbucket.org/xerial/sqlite-jdbc
I'm really puzzled. Is there some kind of persistent cache for this particular JDBC driver? or is it something I missed regarding JDBC in general?
CODE SAMPLE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class SqliteJDBCTest {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
try {
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite::resource:jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite");
System.out.println("connection = " + connection);
statement = connection.createStatement();
System.out.println("statement = " + statement);
rs = statement.executeQuery(" SELECT * FROM nonexistentTable WHERE key = 'nonexistentKey'");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
The above code sample shows the first step of the problem: on the first run, DriverManager.getConnection(..) throwed an exception as expected:
$ java -jar sqliteJDBCTest.jar
java.sql.SQLException: failed to load jar:file:doesntexistJAR.jar!/doesntexistDB.sqlite: java.io.FileNotFoundException: doesntexistJAR.jar (Aucun fichier ou dossier de ce type)
at org.sqlite.Conn.open(Conn.java:92)
at org.sqlite.Conn.<init>(Conn.java:57)
at org.sqlite.JDBC.createConnection(JDBC.java:77)
at org.sqlite.JDBC.connect(JDBC.java:64)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at SqliteJDBCTest.main(SqliteJDBCTest.java:18)
But, since then, for each run I get the following output:
>java -jar sqliteJDBCTest.jar
connection = org.sqlite.Conn#3fee733d
statement = org.sqlite.Stmt#5acf9800
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: nonexistentTable)
at org.sqlite.DB.newSQLException(DB.java:383)
at org.sqlite.DB.newSQLException(DB.java:387)
at org.sqlite.DB.throwex(DB.java:374)
at org.sqlite.NativeDB.prepare(Native Method)
at org.sqlite.DB.prepare(DB.java:123)
at org.sqlite.Stmt.executeQuery(Stmt.java:121)
at SqliteJDBCTest.main(SqliteJDBCTest.java:23)
In this example, the SQLException "SQL error or missing database" is not the error we're expecting!
Not only is the database missing, but even the JAR file supposed to contain it!
So how come getConnection() doesn't throw an exception in the first place?
Short answer: because of a bug in the Xerial JDBC driver.
When one requests the Xerial driver a connection by calling DriverManager.getConnection(jdbc:sqlite::resource:jar:file:<local_location_of_JAR>!/<name_of_database_file>), the driver creates a copy of the database file on the temporary directory specified by the Java system property java.io.tmpdir and then operates on this copy.
The problem is that when the original JAR is removed, the driver loads the copy the next time(s) one uses the same getConnection() call. For me, this is a bug; the driver should at least check that the (possibly remote) JAR file pointed to by the URL is still there...
Second problem (the one described in the CODE SAMPLE of this post): when the original JAR file doesn't exist, a "copy" of the (non-existent) database is created, and the next time(s) getConnection() is called with the same parameters, the driver directly returns a phantom connection to this empty database that was never found...
I submitted this story in a bug report on the Xerial JIRA website:
https://bitbucket.org/xerial/sqlite-jdbc/issue/158/drivermanagergetconnection-not-returning

how to link java and mysql

I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?
import java.sql.*;
class Test{
public static void main(String arg[]){
try{
String query="select * from photo ";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/mydb","user","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
rs.next();
String sname=rs.getString(2);
System.out.println(sname);
con.close();
}
catch(Exception e)
{
System.out.println("error ");
}
}
}
First of all remove the space at the end of the query
String query="select * from photo ";
Next try giving the port in the url
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
you need to add the mysql-connector.jar in your classpath.Get the jar from here
Well if you are using command prompt you can run like this
java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className
If you are using elipse then download the jar and add it to the classpath like this
Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done
1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost"
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
2> should download and add mysql-connector-java to library
Hope this would help

Categories