java.sql.SQLException: No database selected - but it is in the URL - java

I've been researching this for hours and understand that the database schema name should be in the URL. I have it in the URL, but I am still getting this error.
I am using Eclipse and Tomcat v9.0 and sql-connector version 8.0.28.
I have ensured to add the SQL connector everywhere, such as the Build Path, in the Tomcat Folder, in the Tomcat Server configuration, and I am still unable to access it.
In my web.xml I have the following:
<context-param>
<param-name>dbURL</param-name>
<param-value>jdbc:mysql://localhost:3309/logs</param-value>
</context-param>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
In my DBConnection class, I am able to successfully connect to the database with the following code:
package com.algonquin.loggy.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
public class DBConnection {
// Database Schema
// CREATE DATABASE loggy DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
// CREATE TABLE logs (uuid CHAR(40) NOT NULL PRIMARY KEY, title CHAR(128),
// content TEXT, createTimestamp Date);
private static final String dbUser = "root";
private static final String dbPassword = "mypassword";
private static final String conString = "jdbc:mysql://localhost:3309//logs";
public static Connection getConnectionToDatabase() throws ClassNotFoundException {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// get hold of the DriverManager
connection = DriverManager.getConnection(conString, dbUser, dbPassword);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connection made to DB!");
}
return connection;
}
public static void main(String[] args) throws ClassNotFoundException {
getConnectionToDatabase();
}
}
Would greatly appreciate any support that can be given!

Related

How to get some data from a restful web service, and save it to the database?

I have written some code to save some data into database by restful web services, utilizing SOAPUI as user interface. I use #put to do that. Here is the steps of running:
1- run the code on Tomcat 9.0 server.
2- use the URL in SOAPUI to PUT some data.
But when I use PUT in SOAPUI, give the string values of first and last, and run it, the values are not added to my database. Hoewer, the json file got the right values
{
"first": "Jon",
"last": "Snow"
}
Here is the important pieces of my code:
package tomcat.rest.eclipse.database;
public class Score {
public static String first, last;
}
public class ScoreService {
#PUT
#Path("/score")
#Produces("application/json")
public String update(#QueryParam("first") String first,
#QueryParam("last") String last) {
Score.first = first;
Score.last = last;
final String var1 = Score.first;
final String var2 = Score.last;
database.insert(var1, var2);
String pattern = "{ \"first\":\"%s\", \"last\":\"%s\"}";
return String.format(pattern, Score.first, Score.last);
}
}
And this is my connection :
public class database {
public static Connection getConnection() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "00000";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("Connected");
return conn;
} catch(Exception e) {System.out.println(e);}
return null;
}
public static void insert(final String var1, final String var2) {
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO student (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch(Exception e) {System.out.println(e);}
finally {
System.out.println("Insert completed");
}
}
}
The output on console is:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
java.lang.NullPointerException
Insert completed
How can I connect the web service to database properly to save some records in database? Thank you so much for helping me.
Just download and add the mysql connector jar to your project build path.
Or
Add the jar file to your WEB-INF/lib folder. Right-click your project
in Eclipse, and go to "Build Path > Configure Build Path" Add the "Web
App Libraries" library This will ensure all WEB-INF/lib jars are
included on the classpath.
Or the jdbc mysql maven dependency if you use maven :
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
Edit: right click on your project => Build Path => Configure Build
Path => tab "Libraries" and you click on "Add External JARs" and you
point to your file "mysql-connector-java-5.1.17-bin.jar"
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.EmptyStackException;
public class SingletonConnection {
private static Connection connection = null ;
static
{
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/dbnameX","root","");
}catch(Exception ex)
{
}
}
public static Connection getConnection() throws Exception {
return connection;
}
}

Not able to Enable Query Accelerator for DB2 for IDAA from Java

I'm trying to execute SQL queries in query accelerator mode from Java using plain JDBC approach. That is, creating a connection from DriverManager and executed query. But it's getting failed throwing com.ibm.db2.jcc.am.SqlSyntaxErrorException
I set the special parameter in connection URL as mentioned in IBM docs for this.
Tables are already moved to IBM DB2 Analytics Accelerator (IDAA) server and I'm able to execute queries with accelerated mode from AQT tool (My DB client tool) and it is running ultra fast.
I've used db2jcc4 driver Type4 and the connection URL and Connection class is given below:
public class ConnectionManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionManager.class);
private static String url = "jdbc:db2://myIP:myPort/myDBName:specialRegisters=CURRENT QUERY ACCELERATION=ELIGIBLE";
private static String driverName = "com.ibm.db2.jcc.DB2Driver";
private static String username = "user";
private static String password = "pwd";
private static Connection con;
private static String urlstring;
public static Connection getConnection() throws SQLException, ClassNotFoundException {
try {
Class.forName(driverName);
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException ex) {
// log an exception. fro example:
System.out.println("Failed to create the database connection.");
throw ex;
}
} catch (ClassNotFoundException ex) {
// log an exception. for example:
System.out.println("Driver not found.");
throw ex;
}
return con;
}
}
Is there anything I missed or did wrong?
com.ibm.db2.jcc.am.SqlSyntaxErrorException: [jcc][10165][10051][4.24.92] Invalid database URL syntax: jdbc:db2://IP:Port/DBName:specialRegisters=CURRENT QUERY ACCELERATION=ELIGIBLE. ERRORCODE=-4461, SQLSTATE=42815
at com.ibm.db2.jcc.am.b6.a(b6.java:810)
at com.ibm.db2.jcc.am.b6.a(b6.java:66)
at com.ibm.db2.jcc.am.b6.a(b6.java:98)
at com.ibm.db2.jcc.DB2Driver.tokenizeURLProperties(DB2Driver.java:950)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:413)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:113)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at colruyt.spcpocxpsejb.util.ConnectionManager.getConnection(ConnectionManager.java:38)
at colruyt.spcpocxpsejb.util.TestUtility.testAOT(TestUtility.java:98)
at colruyt.spcpocxpsejb.util.TestUtility.main(TestUtility.java:25)
Caused by: java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at java.util.StringTokenizer.nextToken(StringTokenizer.java:377)
at com.ibm.db2.jcc.DB2Driver.tokenizeURLProperties(DB2Driver.java:938)
... 7 more

mySQL connection won't work

I just can't connect to mySQL using Eclipse and can't figure out why.
Here is my connection class :
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ConnexionBDD {
static String url = "jdbc:mysql://localhost:8888/Peoples?autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "";
static Connection connection = null;
static Statement statement = null;
static ResultSet result = null;
static String request = "";
public static void main (String[] args) {
System.out.println("will load driver");
loadingDrive();
System.out.println("will connect");
connection();
}
public static void loadingDrive() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch ( ClassNotFoundException e ) {
e.getMessage();
}
}
public static void connection() {
try
{
connection = (Connection) DriverManager.getConnection(url, login, password);
System.out.println("Connected");
statement = (Statement) connection.createStatement();
result = statement.executeQuery(request);
}
catch ( SQLException e )
{
System.out.println(e.getMessage());
} finally {
if ( result != null ) {
try {
result.close();
} catch ( SQLException ignore ) {
}
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
if ( connection != null ) {
try {
connection.close();
} catch ( SQLException ignore ) {
}
}
}
}
}
Here is the result in the console :
will load driver
will connect
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
I have the connector (mysql-connector-java-5.1.41-bin.jar) in the file WebContent/WEB-INF/lib.
I installed mySQL on my mac.
I installed MAMP, I can reach phpmyadmin and add a new database, but it's kind of weird though, phpmyadmin is already logged as default and clicking the "Exit" button does not disconnect me I don't know why..
The url of phpmyadmin is :
http://localhost:8888/phpmyadmin/index.php
Why can't I connect to mySQL ?
EDIT :
I changed my url with the right port (8889) after checking out the mySQL port on MAMP, but nothing changed in the output of the console.
MySQL and phpMyAdmin cannot be on the same port.
Are you sure that your MySQL is not running on the default port? 3306
UPDATE:
If you are not already using Maven, please do so. It will aid you in managing your packages. That way you can avoid your method: loadingDrive()
I just ran you code locally with a test database. It runs fine for me.
I did the following changes to your code:
I removed the loadingDrive()
Altered request to static String request = "SELECT 1";. This query string is good for testing if the connection to the database is working properly.
I printed the request to the console:
result = statement.executeQuery(request);
System.out.println(result.next());
I added the mysql jdbc connector to my pom.xml file:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
After this I ran the code and this is the console output:
will connect
Connected
true
I still think your MySQL port is wrong. Do you run MySQL locally? Can you connect to it with phpMyAdmin?
I tried to change the url to contain the wrong port. I then received:
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
So I strongly believe that your port is wrong. Can you try to change your url to the following?
static String url = "jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false";

Not able to login through mysql database in Openshift

I have created a java login application with mysql database and deployed it on OpenShift.
URL: http://passwordbucket-king003.rhcloud.com/SimpleLoginTest/
while trying to running its simply showing a blank page with URL-http://passwordbucket-king003.rhcloud.com/SimpleLoginTest/loginservlet .But ideally it should show the home page. Here is my database connection file, please let me know that where I wrong?
package database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection
{
// private final String host = "jdbc:mysql://localhost:3306/logindemo";
// private final String username = "root";
// private final String password = "root";
private final String OPENSHIFT_MYSQL_DB_PORT = "3306";
private final String OPENSHIFT_MYSQL_DB_HOST= "127.3.110.129";
private final String OPENSHIFT_MYSQL_DB_PASSWORD= "root";
private final String OPENSHIFT_MYSQL_DB_USERNAME= "root";
private final String OPENSHIFT_MYSQL_DB_URL= "jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/logindemo";
public Connection con = null;
public Connection openConnection()
{
try
{
Class.forName("com.mysql.jdbc.Driver");
// con = DriverManager.getConnection(host, username, password);
con = DriverManager.getConnection(OPENSHIFT_MYSQL_DB_URL);
}
catch(ClassNotFoundException ex)
{
System.out.println(ex);
}
catch (SQLException ex)
{
System.out.println(getClass().getClass()+" = " +ex.toString());
}
return con;
}
public void closeConnection() throws SQLException
{
if(!con.isClosed()){
con.close();
}
}
}
First of all, on OpenShift your application should be deployed as ROOT.war and there should be content at the "/" context.
Second, if you want to read and use environment variables, you should use System.getenv(). For example:
private final String OPENSHIFT_MYSQL_DB_HOST = System.getenv("OPENSHIFT_MYSQL_DB_HOST);
Your connection URL should also contain the credentials given to you when you created the database.
The database name is probably "passwordbucket" the same as your application name.
In stead of using a jdbc connection you should consider using the JNDI datasource that comes preconfigured on OpenShift. Please check the documentation. You disd not specify the container type you are using.

Connecting to Derby using JDBC

I am trying to connect to Derby database on my locahost using JDBC.
I have started the database using the command: java -jar lib;derbyrun.jar server start, which starts successfully on port 1527.
On another command terminal, I use the command: java -classpath .;lib;derbyclient.jar testsqldatabase.TestSQLDatabase but I get the error below:
java.sql.SQLException: No suitable driver found for jdbc:postgresql:COREJAVA
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at testsqldatabase.TestSQLDatabase.getConnection(TestSQLDatabase.jav
)
at testsqldatabase.TestSQLDatabase.runTest(TestSQLDatabase.java:39)
at testsqldatabase.TestSQLDatabase.main(TestSQLDatabase.java:26)
My datatbase.properties file contains the following lines:
jdbc.drivers=org.postgresql.Driver
jdbc.url=jdbc:postgresql:COREJAVA
jdbc.username=dbuser
jdbc.password=secret
The java program is is listed below:
public class TestSQLDatabase
{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
try
{
runTest();
}
catch(SQLException ex)
{
for(Throwable t: ex)
t.printStackTrace();
}
}
/*Runs a test by creating a table, adding a value,
showing the table contents, removing the table*/
public static void runTest() throws SQLException, IOException
{
try(Connection conn = getConnection())
{
Statement stat = conn.createStatement();
stat.executeUpdate("CTEATE TABLE Greetings (Message CHAR(20))");
stat.executeUpdate("INSERT INTO Greetings VALUES ('Hello, World!')");
try(ResultSet result = stat.executeQuery("SELECT * FROM Greetings"))
{
if(result.next())
System.out.println(result.getString(1));
}
stat.executeUpdate("DROP TABLE Greetings");
}
}
/*
* Gets a connection from the properties specified in the
* file database.properties. #return the database connection
*/
public static Connection getConnection() throws SQLException, IOException
{
Properties props = new Properties();
try(InputStream in = Files.newInputStream(Paths.get("database.properties")))
{
props.load(in);
}
String drivers = props.getProperty("jdbc.drivers");
if(drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username, password);
}
}
Can anyone figure out why I am getting that error from the second command terminal?
Thanks, much appreciated
Derby is a database. PostgreSQL is a different database. You're running a Derby database and you need the corresponding Derby JDBC driver to talk to it - not the PostgreSQL one.
You want to connect to Derby by using the PostgreSQL driver (in the properties file); also the URL of the database is no written well; it should be: jdbc:${dataBaseVendor}:${server}:${port}/${databaseName} where in your case databaseVendor=derby.
And also make sure you have the Derby JDBC driver jar on your classpath.

Categories