Connecting to MySQL via JSP - java

I am trying to establish a connection to a MySQL database to read and write data.
However, I get an error when trying to run this code:
public void openConnection() throws SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/jared_bookoo", "root", "pass");
Statement stmt = conn.createStatement();
}
The weird thing is, all my tests pass when I run a JUnit test. I am able to read from the database correctly and return the correct data. However, once I hook it up to a JSP and try to read it from a locally hosted webpage, I get the following error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/jared_bookoo
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at jared.simpledatabase.DBInterface.openConnection(DBInterface.java:42)
...
What is happening, and how can I fix it? The driver is installed (and working; I can read from the database in my tests), so I don't see what could be going wrong.

Put the MySQL driver jar in your WEB-INF/lib library. You can find it here. Also, make sure that when you generate the war file, the MySQL driver jar is in web_app_name/WEB-INF/lib.
Another advice (just in case since you don't specify where you call that method): You should never try to use Java code directly in your JSP. For further info, refer to How to avoid Java code in JSP files?.
One more advice, in real world web applications, you would use a Data Source to get the Connection. Since you don't specify which application server you use, I'll let an example about configuring the Data Source in Tomcat 7.

Related

SQL Java Data connection

I having difficulty sequencing the class path for the jars, url for Microsoft SQL Express 2019 into a java method. I haven’t been able to connect the drivers to open and execute sql file within java module, the new JDBC Requirements is causing a run error. This also occurwhen running on access. Can some provided a thorough explanations so I can think of what I might have coded in the connection url.

How to fix: Embedded H2 Database "NonTransientError: Unable to read the page at position" error?

I am creating a JavaFX program with an embedded H2 database that will be used to handle user logins and passwords. Using Intellij Ultimate, I have a database that I can run from the toolbar. In addition, I am almost certain I have the correct JDBC driver and URL. The database runs fine from Intellij's database console. The error occurs when I try to access the database with Java code. I am using a database class to handle my database connection.
I am receiving a JdbcSQLNonTransientException, General error:
Illegal state exception: unable to read the page at position
Caused by: java.lang.IllegalStateException: Unsupported type 17.
The line of code that is shown in my compiler, causing the error:
Connection conn = DriverManager.getConnection(DB_URL, "sa", "");
I have tried finding a similar issue everywhere but cannot find related problems. I have tried simplifying my class as much as possible to isolate the problem and simply establish a connection. I deleted my project and tried to start fresh.
Simplified DatabaseManager class that produces the problem:
public class DatabaseManager {
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:D:/trant/Documents/Java Practice/Order A Car2/res/userDatabase";
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection(DB_URL, "sa", "");
Statement st = conn.createStatement();
st.executeUpdate("SELECT * FROM JOBS");
conn.close();
}
}
I expect to connect to an H2 database and retrieve data from the table "JOBS". The code is not compiling with the above errors.
edit: If I use version 1.4.199 of H2 rather than 1.4.200, the issue goes away. I found an almost identical problem here: https://github.com/h2database/h2database/issues/2078. This link has an identical stack trace to mine. I have yet to resolve the problem with version 1.4.200
https://github.com/h2database/h2database/issues/2078
you should use the same driver, so reading it with 1.4.200 (current spring data version) is not possible after modification with 1.4.196 (used by IDEA). So mine crash scenario was open db in IDEA with driver 1.4.196 while spring application code used 1.4.200. So it will not start again. You can declare 1.4.196 version in pom.xml for your app but it looks like that you will be bounded to this version and I don't know how you can completely repair your db.
As already noted by #Yura , you need to ensure that all your code base and all your tools use the same version of the driver, be it 1.4.196 or 1.4.200.
Next, if there was nothing valuable in your db, you can safely drop the db file, and it will be re-created again.
If you had some valuable data and you have no backup, then getting the db repaired may become a quest, not necessarily successful...
And if you have a backup, then a procedure of "backup-to-sql-using-196" and "restore-from-sql-using-200" is most likely to do the job for you, see http://www.h2database.com/html/tutorial.html#upgrade_backup_restore ...
First of all you have to keep a copy of your database somewhere safe.
Copy a fresh copy to your project to avoid any corruption, make sure you don't try to open it using inteliJ.
Go to datasources and drivers ->Drivers -> H2 ->Driver files, change it to 1.4.196.
Create a new datasource of type h2 and fill in the fields
user: "sa"
password:"" (empty)
url is in this form (path to your database file)
jdbc:h2:file:D:\Downloads\loans\loans\Database
then click on test connection and it should show a green message. Apply and close.
Right click on your database in the database view in the editor, then "Open query console". Run this line (link where you want to dump your database)
SCRIPT TO 'D:\Downloads\loans\loans\db-dump.sql'
Create a new database file (Test.mv.database), follow the previous steps and change the driver version back to 1.4.200. Create a new datasource with the same steps this time linking to your new database
jdbc:h2:file:D:\Downloads\loans\loans\Test
Test the connection, Apply and close.
Open the query console and copy paste the script from db-dump.sql and run it. Right click on the database in the database view and click "Refresh". You should see the data. Right click again and click "Disconnect".
Make sure your application.properties file is pointing to the correct database(Test) and run your application.
You really should provide a complete stack trace and not just the error message in such questions.
And message that you see is not a compilation error.
Usually such message means that your database is corrupted. If you don't need any data from it, you can simply delete all its files and re-create it from the scratch.
If you can open the database from some tool, but cannot open it from your application, check the versions of H2 that are used in both places and align them. You can export the database in version that works to an SQL script with SCRIPT TO 'filename.sql' command and use that script to populate the data into new database to make sure that it isn't damaged (with the version that you prefer).
If you don't want to alter pom or change h2 version then try deleting the file:
userDatabase.mv.db
userDatabase.trace.db
You may find these files inside dir "D:/trant/Documents/Java Practice/Order A Car2/res/".
But before delete ensure that there is no active connection to the db from anywhere else. If not sure then delete just after restarting the machine.
After all done, try running the code again. Those files will be re-generated by pom
I've reproduced the same issue:
java.lang.IllegalStateException: Unable to read the page at position
while connecting to H2 db using Data Source via connection URL:
jdbc:h2:file:./data/testdb;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE
using dependency:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
After some investigations the way how to solve the problem was found.
Solution:
So, firstly, I changed version of dependency in POM to:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
Secondly, fully recreated Data Source configuration with the same connection URL:
jdbc:h2:file:./data/testdb;DB_CLOSE_ON_EXIT=FALSE;AUTO_SERVER=TRUE
with removing Data Base files for old driver (it'll be regenerated after new connection):
After recreation configuration in Data Source using new driver, checking connection and as result it works for me:
Firstly launch your h2 db and than start your application.

No suitable driver found for jdbc:db2 with db2jcc4.jar present in web-inf\lib

I am trying to run a simple java web app that connects to a back end DB2 database(IBM dashdb) to get retrieve some data.
I am getting a weird error message when I try to run this application on a ubuntu hosted tomcat 8.5.
I managed to get this application running on a tomcat v8 hosted on Windows.
The actual error message is:
No suitable driver found for jdbc:db2://yp-dashdb......
I don't really understand why this is happening because I have the db2jcc4. in my web-inf\lib folder.
I thought it was something wrong with the library so I created a separate Java app to simply connect and retrieve some data from the database. That one works just fine with the same library.
This is the code used to set up the connection (I trimmed out some of the details).
private Connection conn = null;
conn= DriverManager.getConnection("jdbc:db2://yp-dashdb...");
Keep in mind, that this exact same code works in a Standard Java app so the connection details work and there's no typo in the connection info.
Is there something obvious that I'm overlooking here?
After spending some time trying to figure this one out I find out the problem. My drivers were not being registered by DriverManager. The quick fix I found for this was to manually register it before trying to load the driver.
DriverManager.registerDriver(new com.ibm.db2.jcc.DB2Driver());
This has solved my issue. The way I found out about this was to print out all the registered drivers and print them out. Not the most elegant solution but it helped me find out what I'm missing.
/*
System.out.println("checking for drivers");
Enumeration<Driver> myDrivers = DriverManager.getDrivers();
System.out.println(myDrivers.hasMoreElements());
while(myDrivers.hasMoreElements()){
System.out.println(myDrivers.nextElement().toString());
}
*/
WEB-INF/lib is in your application. It might be so that tomcat needs this driver before your app is loaded? Try putting it into the tomcat's lib folder and restarting...
Here is another question on the same topic: Why must the JDBC driver be put in TOMCAT_HOME/lib folder?

Where exactly should JDBC URL value be changed?

I'm trying to run some application and get the following error:
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for
JDBC]Can't start a cloned connection while in manual transaction mode.
I know that I should add the parameter ;SelectMethod=Cursor to your JDBC URL
But I'm having problem understanding where exactly should I change it? Should it be some conf file in JDBC driver folder somewhere? Or can I do it from sql management studio?
Also is there some easy way to determine if and what version of JDBC driver I have?
Help is very much appreciated!
You specify the URL when creating your JDBC connection, e.g.:
Connection con = DriverManager.getConnection(
"jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]",
username,
password);
Of course you have to replace the stuff in the brackets with your values.
Quite the same is true for every other tool (e.g. IntelliJ, Eclipse) I know of that connects to a DB via JDBC. See e.g. attached screenshot. Here you also specify the connection parameters via the JDBC URL.

Error while connecting to Oracle DSN using Java

I need to develop an application that connects to various DSN's using the Microsoft ODBC drivers. I have developed the application in Eclipse and it seems to work properly. The connection succeeds and I am able to view table data.
However when I export the project to a runnable jar file (using Eclipse) the functionality fails for Oracle. It is unable to establish connectivity with the Oracle connection string. It still works for SQL server but fails in case of Oracle. I'm unable to figure out the cause as the same ODBC drivers are being used for both Oracle and SQL-Server. More mystifying is that it runs properly on Eclipse. Since im using the ODBC drivers I don't believe the problem is because of an external jar file.
The driver is sun.jdbc.odbc.JdbcOdbcDriver and connection string is like jdbc:odbc:oratest;user=fell;password=pass.
I'm getting the following exception
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6958)
Can you please help me figure what the problem might be?
Thanks in advance,
Fell
Create a System DSN.
java.sql.Connection cn;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
cn=java.sql.DriverManager.getConnection("jdbc:odbc:dsn_name","user","pass");
Check the classpath in the eclipse project

Categories

Resources