Servlet with JDBC [duplicate] - java

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 5 years ago.
I have a problem with my progect. Files of progect:
House.class
public class House implements Serializable {
//properties -------------------------------------------------------------
private String price;
private String square;
private String RoomNumbers;
//------------------------------------------------------------------------
//getters - settersm Object overriding.... -----------------------------
HouseDAO.class
public class HouseDAO {
Connection connection;
final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb2";
final String DB_USER = "root";
final String DB_PASSWORD = "root";
public HouseDAO(Connection connection) {
this.connection = connection;
}
public List<House> getList() {
List<House> houses = new ArrayList<>();
try {
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection available");
PreparedStatement ps = connection.prepareStatement("SELECT Square, RoomNumbers, Price FROM houses WHERE District = 'Dnepr'");
ResultSet rs = ps.executeQuery();
while (rs.next()){
House house = new House();
house.setSquare(rs.getString("Square"));
house.setRoomNumbers(rs.getString("RoomNumbers"));
house.setPrice(rs.getString("Price"));
houses.add(house);
}
}catch (Exception ex){
System.out.println("SQL exceprion");
ex.printStackTrace();
}
return houses;
}
}
and Servlet:
HousesBaseServlet
#WebServlet("/post")
public class HosesBaseServlet extends HttpServlet {
Connection conn;
private HouseDAO houseDAO;
#Override
public void init(){
houseDAO = new HouseDAO(conn);
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
//choice from html form
// String choice = request.getParameter("district");
try {
List<House> houses = houseDAO.getList();
request.setAttribute("houses", houses);
request.getRequestDispatcher("/houses.jsp").forward(request,response);
}catch (Exception ex ) {
System.out.println("Fail to connect with base");
ex.printStackTrace();
}
}
}
I was read some solutiotuns, but it doesn't help. The problem in two exceptions:
SQL exceprion java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/mydb2
I try to add:
Class.forName("com.mysql.jdbc.Driver");
to my code, and add mysql connector jar to my project, but it throws exception:
SQL exception java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Second exception:
JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core
cannot be resolved in either web.xml or the jar files deployed with
this application Fail to connect with base
Here is my pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
,
JSP taglib:
%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %
and project structure:
[project structure][1]
Project structure - artifacts
In project structure -> libraries i have all jars.

Since you are using IntelliJ I believe you might need to add the libraries to the artifact because from my experience Intellij adds the maven dependencies to the Classpath but not to the artifact.
Make sure you go to File -> Project Structure -> Artifacts and then add all the libraries from the available side to the artifact.
But you need to register the driver before getting the connection otherwise it doesn't work either way :
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
Hope this helps.

Related

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

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!

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

Java, Maven, connect SQL , no suitable driver

I am building a project using Netbeans IED, with java. The project is using maven and I am attempting to connect it to sql database which I am having issue's. The code works in java but not with maven.
Here the error:
No suitable driver found for jdbc:derby://localhost:1527/Database
Java Code:
public class DatabaseTest {
public static Connection ConnectionObj = null;
public static Statement SqlStatement = null;
public static ResultSet Sqlresult = null;
public static ResultSetMetaData MetaData = null;
public static String query = "Select * from Wallet";
public static String url = "jdbc:derby://localhost:1527/Database";
public static String user = "ABM";
public static String pass = "password2";
public static void main(String[] args) {
try {
//Allows you to connect the database
ConnectionObj = DriverManager.getConnection(url, user, pass);
SqlStatement = ConnectionObj.createStatement();
Sqlresult = SqlStatement.executeQuery(query);
MetaData = Sqlresult.getMetaData();
System.out.println("Connection worked");
} catch (SQLException e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
Prom depency's:
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<version>10.14.1.0</version>
</dependency>
https://gyazo.com/8937aada3bd4a8f5b108b5dc9b386dd7
This part of your POM file is incorrect:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
Your program is attempting to use JDBC to connect to a Derby database, so you should be using a Derby JDBC driver, not a MySQL JDBC driver.
Replace the above with the following:
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derbyclient</artifactId>
<version>10.14.1.0</version>
</dependency>
(Use the same version as your main Derby version ...)
The code works in Java but not with Maven.
Curious. Perhaps you are setting the runtime classpath correctly in the Java case.

Exception with com.mysql.jdbc.Driver

i'm trying run code
public static Connection getConnection() throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql?zeroDateTimeBehavior=convertToNull [root on Default schema]");
} catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null,e.toString());
}
return cn;
}
but i get the exception:
with the dialog:
I have added the divier :mysql-connector-java-5.1.36-bin.jar in this project.
What am I doing wrong?
Add mysql connector jar to your project classpath.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>

Using MS-SQL With Maven2, Netbeans on a (Mac or Linux)

Looking for advice or a bit of help, to point me in the right direction.
I need to connect to a Microsoft SQL Server from a Java program, however, the drivers must be available in maven2 and work with NetBeans.
Any advice? (pointer to an example would be great) (Suicide is no longer an option)
Edit: I've found JTDS- is this a good solution?
Edit 2: Looks like it works... Here is how I have it configured...
Pom file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.steward.ccd</groupId>
<artifactId>amalgainterface</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>amalgainterface</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.ini4j</groupId>
<artifactId>ini4j</artifactId>
<version>0.5.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
</project>
Java File
import java.sql.*;
import org.ini4j.*;
import java.util.*;
import java.io.File;
public class AmalgaInterface {
public static void main(String[] args) {
// MS-SQL Parameters
String db_name = "xxxx";
String db_hostname = "xxxx";
String db_port = "1433";
String db_userid = "xxxx";
String db_password = "xxxx";
String db_timeout = "10";
// Check the Configuration file, and replace all service reference as required.
// Get configuration
String configFile = "/etc/test.conf";
// Load data from INI files
Ini ini = null;
try {
ini = new Ini(new File(configFile));
db_name = ini.get("database", "name");
db_hostname = ini.get("database", "host");
db_userid = ini.get("database", "user");
db_password = ini.get("database", "pass");
db_port = ini.get("database", "port");
db_timeout = ini.get("database", "dbtimeout");
} catch (Exception ex) {
System.out.println("Cannot load the configuration file");
}
// Create the connection string
String db_connect_string = "jdbc:jtds:sqlserver://" + db_hostname + ":" + db_port + "/" + db_name + ";socketTimeout=" + db_timeout;
// setup connection
Connection connection = null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connection = DriverManager.getConnection(db_connect_string, db_userid, db_password);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
// clean up
if (connection != null) {
try {
connection.close();
} catch (Exception ex) {
}
}
}
}
Try JTDS
It's a type 4 jdbc driver and I believe it's available via maven repository.

Categories