Connection with mysql with netbeans for jsp [duplicate] - mysql

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
How should I connect to JDBC database / datasource in a servlet based application?
(2 answers)
Closed 2 years ago.
I am using NetBeans 7.0.1 IDE for JSP/servlet
I am trying to make a database connection for my project. Already downloaded the jar file 'mysql-connector-java-5.1.24-bin.jar' pasted it to jdk's jre/lib dir, also added it to my netbean projects libraries dir.
then I created a servlet and wrote the following code:
import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class tstJDBC extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
String dbURL = "jdbc:mysql://localhost:3306/murach";
String username="root";
String password="1234";
Connection con2 = DriverManager.getConnection(dbURL, username, password);
String query = "insert into tblUser1(firstname) values('shaon')";
Statement statmnt = con2.createStatement();
statmnt.executeUpdate(query);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
But it can establish the connection. From the line Connection con2, its directly going to catch() block ; without executing the query.

Try loading the driver prior to using the DriverManager class.
try{
String dbURL = "jdbc:mysql://localhost:3306/murach";
String username="root";
String password="1234";
Class.forName("com.mysql.jdbc.Driver");//load driver
Connection con2 = DriverManager.getConnection(dbURL, username, password);
String query = "insert into tblUser1(firstname) values('shaon')";
Statement statmnt = con2.createStatement();
statmnt.executeUpdate(query);
}
From O'Reilly:
Before you can use a driver, it must be registered with the JDBC
DriverManager. This is typically done by loading the driver class
using the Class.forName( ) method:
This is required since you have placed the library within the JDK/lib folder which I'm assuming is loaded using a different ClassLoader than the one used by your application. Since different class loaders were used the automatic registration that takes place by JDBC 4.0+ drivers will not take effect. You could try to place the driver jar file within the lib of your application server, which should use the same ClassLoader of your application. See: When is Class.forName needed when connecting to a database via JDBC in a web app?
Regarding Automatic Registration
In JDBC 4.0, we no longer need to explicitly load JDBC drivers using
Class.forName(). When the method getConnection is called, the
DriverManager will attempt to locate a suitable driver from among the
JDBC drivers that were loaded at initialization and those loaded
explicitly using the same class loader as the current application.
The DriverManager methods getConnection and getDrivers have been
enhanced to support the Java SE Service Provider mechanism (SPM).
According to SPM, a service is defined as a well-known set of
interfaces and abstract classes, and a service provider is a specific
implementation of a service. It also specifies that the service
provider configuration files are stored in the META-INF/services
directory. JDBC 4.0 drivers must include the file
META-INF/services/java.sql.Driver. This file contains the name of the
JDBC driver's implementation of java.sql.Driver. For example, to load
the JDBC driver to connect to a Apache Derby database, the
META-INF/services/java.sql.Driver file would contain the following
entry:
org.apache.derby.jdbc.EmbeddedDriver
Let's take a quick look at how we can use this new feature to load a
JDBC driver manager. The following listing shows the sample code that
we typically use to load the JDBC driver. Let's assume that we need to
connect to an Apache Derby database, since we will be using this in
the sample application explained later in the article:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection conn =
DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
But in JDBC 4.0, we don't need the Class.forName() line. We can simply
call getConnection() to get the database connection.
Source
Regarding Service Loaders
For the purpose of loading, a service is represented by a single
type, that is, a single interface or abstract class. (A concrete class
can be used, but this is not recommended.) A provider of a given
service contains one or more concrete classes that extend this service
type with data and code specific to the provider. The provider class
is typically not the entire provider itself but rather a proxy which
contains enough information to decide whether the provider is able to
satisfy a particular request together with code that can create the
actual provider on demand. The details of provider classes tend to be
highly service-specific; no single class or interface could possibly
unify them, so no such type is defined here. The only requirement
enforced by this facility is that provider classes must have a
zero-argument constructor so that they can be instantiated during
loading.
A service provider is identified by placing a provider-configuration
file in the resource directory META-INF/services. The file's name is
the fully-qualified binary name of the service's type. The file
contains a list of fully-qualified binary names of concrete provider
classes, one per line. Space and tab characters surrounding each name,
as well as blank lines, are ignored. The comment character is '#'
('\u0023', NUMBER SIGN); on each line all characters following the
first comment character are ignored. The file must be encoded in
UTF-8.
If a particular concrete provider class is named in more than one
configuration file, or is named in the same configuration file more
than once, then the duplicates are ignored. The configuration file
naming a particular provider need not be in the same jar file or other
distribution unit as the provider itself. The provider must be
accessible from the same class loader that was initially queried to
locate the configuration file; note that this is not necessarily the
class loader from which the file was actually loaded.
Source

just Keep the "mysql-connector-java" in "C:\Program Files\Java\jdk1.7.0_25\jre\lib\ext"
the "jdk1.7.0_25" is my version of jdk may be you have different version but will must have the sub folders "\jre\lib\ext" inside that.

Related

Spring Boot App: Login to MySQL database on Azure using system assigned managed identity

I followed this article to create a system assigned managed identity for an app service on Azure and made the necessary AD authrization for MySQL database. The link has a java code to generate token and connect to MySQL, however, that code is not handy to be injected as a Bean to all DAO classes. Moreover, with that code, you need to check expiry of token with almost every call.
Does anyone know an implementation which takes care of renewing token and which can be used as a Bean?
• To be frank, I tried to login to an Azure SQL DB server using a system assigned managed identity from a .Net Framework console application and that truly worked for me, i.e., it responded with code 0 successfully. I also checked further in the application insights workspace to find out whether the connection truly happened or not and the connection was made successfully without any issue.
• Thus, in your scenario, you have deployed a web app service in Azure with code runtime as Java since you want to develop a spring boot app and create a system assigned managed identity to it and an Azure MySql DB server also to connect to. After deploying this infrastructure and following the Github documentation that you have posted, I would suggest you to please include the RestControllerAdvice section under TokenRefreshException.java as below: -
package com.example.spring.security.jwt.advice;
import java.util.Date;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import com.bezkoder.spring.security.jwt.exception.TokenRefreshException;
#RestControllerAdvice
public class TokenControllerAdvice {
#ExceptionHandler(value = TokenRefreshException.class)
#ResponseStatus(HttpStatus.FORBIDDEN)
public ErrorMessage handleTokenRefreshException(TokenRefreshException ex, WebRequest request) {
return new ErrorMessage(
HttpStatus.FORBIDDEN.value(),
new Date(),
ex.getMessage(),
request.getDescription(false));
}
}
This would tell a controller that the object returned is automatically serialized into JSON and passed it to the ‘HttpResponse’ object. You only need to return Java body object instead of ResponseEntity object. But the status could be always OK (200) although the data corresponds to exception signal (404 – Not Found for example).
Hence, using the above section, you can manage the renewing of a token in your spring boot application. For more detailed information on this, I would suggest you to please refer to the below link: -
https://www.javainuse.com/webseries/spring-security-jwt/chap7

Injecting DbContext into FileProvider in ASP.NET Core

I am trying to load some of the views from the database as described in here. So I want to use EF Core in the File provider.
RazorViewEngineOptions has a FileProviders property that you can add your file provider to. The problem is that you have to give it an instace of the file provider. So you'll need to instantiate all of the file providers' dependencies right there in Startup's ConfigureServices method.
Currently I inject an instance of IServiceProvider into the Configure method of Startup. Then I store the instance in a field (called _serviceProvider):
IServiceProvider _serviceProvider;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider provider)
{
_serviceProvider = provider;
...
}
Then in ConfigureServices I use that field to instanciate the UIDbContext.
services.Configure<RazorViewEngineOptions>(options =>
{
var fileProvider = new DbFileProvider(_serviceProvider.GetService<UIDbContext>());
options.FileProviders.Add(fileProvider);
});
Is there any better way to be able to inject the UIDbContext into the DbFileProvider constructor Or any way to instantiate a UIDbContext inside DbFileProvider without IServiceProvider?
You don't want to use DbContext as a file provider source the way you did.
DbContext isn't thread-safe, so it won't work when you have one single DbContext instance for the whole provider, because multiple requests could call the DbContext and it's operation more than once at the same time, resulting in exception when trying to execute 2 queries in parallel.
You'd have to instantiate a connection (like in the linked article) or DbContext per IFileInfo/IDirectoryContents instance.
DbContextOptions<UIDbContext> should be registered as singleton, so you can resolve it onceinside Configure` w/o any issues and pass it to your provider.
Alternatively you can also call DbContextOptionsBuilder and build/construct a DbContextOptions<T>, but then you have to repeat the configuration for you did inside AddDbContext (i.e. .UseSqlServer()).
However it can be useful, as it allows you to set different settings (i.e. changing the way how includes, errors etc. are logged).

Weka Find Database Util Properties But Throwing Driver Not Found

I build a simple weka application using Weka 3.7.13 dev version using MAVEN. I have initialise the pom.xml function to get weka library from the repository.
i want to run a simple clustering algorithm using weka, and connecting it to MySQL database. As per documentation, the weka need to have a DatabaseUtil.props file which contains it's jdbc driver. I have setup that.
This is my project structure:
I can retrieve the DatabaseUtils.props using my code below. But somehow the weka itself cannot recognise the jdbc:Url and driver name which i already configure inside.
DatabaseUtil.props file:
# JDBC driver (comma-separated list)
jdbcDriver=com.mysql.jdbc.Driver
# database URL
jdbcURL=jdbc:mysql://127.0.0.1:3306/datamining
Java code which i trigger the Weka module:
public void dm(){
int cluster = 4;
InstanceQuery clusterQuery = null;
try{
//file reader of database utilities properties
ClassLoader classLoader = getClass().getClassLoader();
File fileProps = new File(classLoader.getResource("DatabaseUtils.props").getFile());
//setup the data preparation functionality then connect to database
clusterQuery = new InstanceQuery();
clusterQuery.setUsername("test");
clusterQuery.setPassword("test");
clusterQuery.setQuery("SELECT * FROM TEMP_KMEANS");
clusterQuery.setCustomPropsFile(fileProps);
But when executed the function returning error: java.sql.SQLException: No suitable driver found for jdbc:idb=experiments.prp
It seems that the DatabaseUtils.props file cannot override the default driver value jdbc:idb=experiments.prp
Any ideas why this is throwing?
Any feedback and answer much appreciated.
I created a DatabaseUtils.props file in the src / main / resources folder and wrote the following code. It worked for me, I'm using weka 3.8.0.
File file = new File(getClass().getClassLoader().getResource("DatabaseUtils.props").toURI());
InstanceQuery query = new InstanceQuery();
query.setCustomPropsFile(file);
query.setUsername(MYSQL_USER);
query.setPassword(MYSQL_PASSWORD);
query.setQuery("select * from Action");
instances = query.retrieveInstances();
System.out.println(instances.toString());
The documentation says "These may be changed by creating a java properties file called DatabaseUtils.props in user.home or the current directory". Your properties file does not match those requirements (a properties file in a jar is not on the filesystem). See also Chapter 14 of the Weka manual.
An alternative solution is to set the URL in code using setDatabaseURL. As long as the JDBC driver is on the classpath this should work.

Why does DriverManager.getConnection() lookup fail in GroovyConsole?

The following Groovy script works correctly from the command line. (I successfully get a Connection.)
// ---- jdbc_test.groovy
import java.sql.*
Class.forName("com.mysql.jdbc.Driver")
def con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test",
"root",
"password")
println con
> groovy -cp lib\mysql-connector-java-5.1.25-bin.jar script\jdbc_test.groovy
com.mysql.jdbc.JDBC4Connection#6025e1b6
But if the same script is loaded into GroovyConsole (2.4.3) and run - after adding the mysql-connector-java-5.1.25-bin.jar using 'Script' | 'Add Jar(s) to ClassPath' - it fails:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
at java_sql_DriverManager$getConnection.call(Unknown Source)
at jdbc_test.run(jdbc_test.groovy:3)
Every other package or class I have added to the classpath in GroovyConsole and experimented with has worked. Is there some unexpected interaction of Groovy's class loading and the way DriverManager works?
Is there a way around this? I'm trying to use the GroovyConsole to interactively test out some JDBC code (a library of functions, each of which takes a Connection as its first argument).
UPDATE: The Class.forName() part appears to be working fine. If I 'Script' | 'Clear Script Context' and rerun the script in GroovyConsole, I instead get:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
If I add mysql-connector-java-5.1.25-bin.jar back in, I go back to getting:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/test
Solution: The driver has to be on the classpath.
Reason:
If you look into the DriverManager class you find code like this: Class.forName(driver.getClass().getName(), true, classLoader);. This is to check if the driver is accessible from your classloader context. And that context is determined by going back to the class that is calling he DriverManager. This code is written for Java, thus assumes a certain amount of frames on the call stack to go back. Since Groovy does not do direct calls (unless you use #CompileStatic) this number is wrong and leads usually to a Groovy core class to be selected, resulting in Groovy main loader to be selected.... in the past this was often even the JDK system classloader because of reflection. So even though the driver is loaded and registered, it is not accessible to you.
Note: with jdbc4 the driver should register itself, just by being on the classpath

Java EE and JPA under Glassfish, NoClassDefFound com/mysql/jdbc/ResultSetMetaData

I have a problem when I acces my MySql Database from an EJB. After deploying my EAR to the Glassfish server, and calling the method that use the entity class I get an exception like this:
java.lang.NoClassDefFoundError: com/mysql/jdbc/ResultSetMetaData
I am using a local MySql Database, the connection to these still works. To acces the tables of these Databese I am using entity classes generated by Netbeans. This classes are situated in external Library (OthelloLibrarie). Here you can also find the remote interface of my Session Bean.
I had to put the entity classes in an external library because I'm using them in an Enterprise Client Application which is connected to my EAR.
My Enterprise Application Project contains the main Session bean and somes Session beans from entity classes which uses my entity classes in the external Library. It also contains the persistence XML and it includes my JDBC driver:
The error appears when I call the method createPartie from the Client Application:
Partie p = eJBOthelloGame.createPartie(jTextFieldPseudo.getText());
SessionBeanOthelloRemote.java:
#Stateless
public class SessionBeanOthello implements SessionBeanOthelloRemote {
#EJB
private PlayerFacadeLocal playerFacade;
#EJB
private PartieFacadeLocal partieFacade;
#Override
public Partie createPartie(String player) {
//Ajout du tuple
Partie p = new Partie();
Player p1 = new Player();
p1.setId(1);
p1.setNom(player);
playerFacade.create(p1);
p.setPlayer1(p1);
partieFacade.create(p);
return p;
}
Partie and Player are Entity classes used with generated facades.
I searched yet on the web but I never found this kind of error. It seems that only the package or class ResultSetMetaData from JDBC has a problem and not the entire driver.
Can you help me?
You need to include in your project the mysql-connector-java.jar file that provides the MySql JDBC driver classes. As you are using Netbeans, just add it as a library jar.
You can find it, along with download and installation instructions, at this link.