I am working on a project where I need to log query in Log files and add those queries to my assert statement as well
I have build prepared statements using below driver
net.sf.log4jdbc.sql.jdbcapi.DriverSpy
And url
jdbc:log4jdbc:sybase:Tds ........
Dependencies I am using is as below:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
PrepareStatement Example:
public void getTest(MyBean bean) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DatabaseUtil.getDatabaseConnection();
ps = conn.prepareStatement(objTestQueryUtil.getQuery("GET_Test"));
ps.setString(1, bean.getTypeOfTest());
ps.setString(2, bean.getTest());
ps.setString(3, bean.getTestState());
ps.setString(4, bean.getTestStep());
rs = ps.executeQuery();
while(rs.next()) {
bean.setTest(rs.getInt("Test"));
}
}catch (SQLException e) {
AutomationLog.error(e.getMessage(),e);
}finally {
DatabaseUtil.close(conn,ps,rs);
}
}
In my assert class, the sql should see in my assert code like:
Assert.assertTrue("Got Test "+query, true);
Can you please tell me if there any way around by which I can get query in variables in java also, currently query directly logs into the log file and I am not able to find anyway by which I can get them in my script, i.e store on any variable etc
Another dependencies or solution are also welcome if current dependencies do not have such provisions for pre-prepared-statements
This is not the optimal solution but it can solve your problem:
Open your jtds jar file (or download the jtds source files and import them in your IDE), find and decompile the class net.sf.log4jdbc.StatementSpy.class,
add a static String variable in that class, let's call it myLastExecutedSQL
edit the reportSQL() method, assign the sql method parameter to your static variable
compile the new class (or regenerate the jar) and use it in your project
in your test class you will be able to access the last executed query with StatementSpy.myLastExecutedSQL
As you're using maven you will have to replace the jar on the maven home folder
The drawback of this is that you cannot use it in a multi-threaded environment, but it will do the trick.
I hope it's clear enough
Related
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.
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);
I had a problem in connecting with the firebirdsql.
here is my code.
try {
Class.forName("org.firebirdsql.jdbc.FBDriver");
Connection con= DriverManager.getConnection("jdbc:firebirdsql:localhost/3050:C:\\EMPLOYEE.FDB","sysdba","masterkey");
Statement stm= con.createStatement();
ResultSet res= stm.executeQuery("SELECT * FROM Emp");
while (res.next()) {
System.out.println("EMPLOYEE NAME:"
+ res.getString("NAME"));
}
} catch (Exception e) {
System.out.println(e);
}
Getting an ERROR like.
java.lang.ClassNotFoundException: org.firebirdsql.jdbc.FBDriver
The java.lang.ClassNotFoundException: org.firebirdsql.jdbc.FBDriver indicates that you do not have Jaybird (the Firebird JDBC driver) on your class path, as Java failed to load the driver class.
You can download Jaybird from https://www.firebirdsql.org/en/jdbc-driver/
You need to make sure that jaybird-full-2.2.12.jar (or jaybird-2.2.12.jar and lib/connector-api-1.5.jar) are on the class path when you run the application.
This means that you either need to include it in the manifest, or you need to explicitly specify it when running Java:
java -cp .;jaybird-full-2.2.12.jar MyClass
Alternatively, if you use Maven, you can include the dependency using:
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird-jdk18</artifactId>
<version>2.2.12</version>
</dependency>
See also the Jaybird JDBC Driver Java Programmer's Manual, specifically chapter 2.
The use of Class.forName("org.firebirdsql.jdbc.FBDriver"); is not necessary with Jaybird 2.2 and higher.
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
When I create a new project in Netbeans, I added the sqlite.jar to the classpath and library. I wrote a short test program and it works great!
Now I want to add a GUI as a front end, so I create a brand new project in Netbeans but I create a swing project and create the GUI using netbeans. The GUI works fine by itself (just taking input and writing it to the console as a test).
So now in the GUI project I go and in the "Source Package" folder I add a new java class and I copy/paste the code from my other (working) sqlite implementation. I also add sqlite to the Classpath/library and nothing works!
This is (part) of the code I have:
package my.test;
import java.sql.*;
public class sqlaccess {
Class.forName ("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
Statement stat = conn.createStatement();
/* commented out the connecting/creating tables etc code */
}
The error I get is this:
C:\Users\xxx\Documents\NetBeansProjects\TestUser\src\my\testuser\sqlaccess.java:12: <identifier> expected
Class.forName ("org.sqlite.JDBC");
C:\Users\xxx\Documents\NetBeansProjects\TestUser\src\my\testuser\sqlaccess.java:12: illegal start of type
Class.forName ("org.sqlite.JDBC");
So I'm pretty sure the problem is the way I combine these 2 classes/files since each one works perfect stand alone.
The problem is this code block:
Class.forName ("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
Statement stat = conn.createStatement();
You need to move this code into a method, a constructor, a static initializer, or something similar. Code cannot be placed directly into the class body in Java.
How about ..
public class sqlaccess {
void init(){
try{
Class.forName ("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:TestUser.db");
Statement stat = conn.createStatement();
/* commented out the connecting/creating tables etc code */
}
catch(ClassNotFoundException ex){
//Handle Exception
}
}
}