Connect PostgreSQL to Java Dynamic Web Project - java

I'm trying to make my java dynamic web project work with postgresql database, but cannot figure out how to do that correctly.
What I did:
create Dynamic Web Project that runs on Tomcat v8.0
download postgresql jdbc driver
throw the postgresql-9.4-1205.jdbc4.jar file into my WEB-INF/lib
folder
create database java_lab2, create user lab2 with password qwerty, grant all privileges to user lab2 and create table users, all in psql
create META-INF/context.xml file
modify WEB-INF/web.xml file
here's my context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/connectorDs" auth="Container"
type="javax.sql.DataSource" username="lab2" password="qwerty"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://localhost:8080/java_lab2"
maxTotal="10" maxIdle="4" />
</Context>
here's what I've added to web.xml:
<resource-ref>
<description>PostgreSQL data source</description>
<res-ref-name>jdbc/connectorDs</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
and now I cannot figure out how to actually start working with the database.
How do I connect to it? How do I query it in my servlets after the connection?
Update
I added the following function to my servlet:
private void attemptConnection() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:8080/java_lab2", "lab2",
"qwerty");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
and run it in doGet method.
This gives me the following output:
PostgreSQL JDBC Driver Registered!
Connection Failed! Check output console
org.postgresql.util.PSQLException: The connection attempt
failed. at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:257)
at
org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:65)
......................
......................
Caused by:
java.io.EOFException at
org.postgresql.core.PGStream.ReceiveChar(PGStream.java:284) at
org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:405)
at
org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:203)
... 35 more

Related

Murach's Java Servlets 3rd edition NullPointerException when writing to database from application

I'm working with Murach's Java Servlets and JSP 3rd edition and have having difficulty with the ch12email project (which can be downloaded from murach.com). My issue is that when running the application and entering data into the form and submitting, I get the following HTTP Status 500 error:
java.lang.NullPointerException
murach.data.ConnectionPool.getConnection(ConnectionPool.java:32)
murach.data.UserDB.emailExists(UserDB.java:80)
murach.email.EmailListServlet.doPost(EmailListServlet.java:39)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Here is where the error is occurring:
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
And that class's constructor:
private ConnectionPool() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/murach");
//dataSource = (DataSource) ic.lookup("jdbc/murach");
} catch (NamingException e) {
System.out.println(e);
}
}
However, I'm able to connect to the database in Netbeans and view or edit data in the database. This is the Resource tag in the context.xml file for the database user and password information:
<Resource name="jdbc/murach" auth="Container"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/murach"
username="root" password="67890"
maxActive="100" maxIdle="30" maxWait="10000"
logAbandoned="true" removeAbandoned="true"
removeAbandonedTimeout="60" type="javax.sql.DataSource" />
I'm not completely sure what information would be needed to thoroughly troubleshoot this problem, so please let me know whatever information would help and I'll be sure to supply it!
Do you have a resource ref defined in web.xml
<resource-ref>
<res-ref-name>jdbc/murach</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I never found a solution, but was able to install it on a Windows 7 VM successfully following the steps in the book as normal. Afterwards I moved all of my files to an external and reinstalled Windows 10 on my laptop (the machine that was having the issue). After that I followed the book's instructions again and it worked. Thank you for anyone that took the time to try to help!

JDBC connection not happening [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
Below is the code I used for jdbc connection
String dbUrl="jdbc:mysql://localhost:3306/mysql";
String user= "kumar";
String pwd="ratiol";
try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
but I got error as below-
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:22)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mysql
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:19)
Can you please tell me how can I get jdbc url?
I am using eclipse(mars) in ubuntu 14.04
if you are using netbeans, right click project -->properties -->libraries-->add library and select MySQL JDBC Driver
just add the com.mysql.jdbc.Driver to the lib folder in you program files.
This is what you wrote
try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
it would be like this:
Connection con = null;
try {
//registering the jdbc driver here, your string to use
//here depends on what driver you are using.
Class.forName("something.jdbc.driver.YourFubarDriver");
Connection connection = DriverManager.getConnection(dbUrl, user, pwd)
} catch (SQLException e) {
throw new RuntimeException(e);
}
Please check Class.forName not more needed when using JDBC v.4
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.
Note that this is for getting a database connection in stand-alone
mode. If you are using some type of database connection pool to manage
connections, then the code would be different.
There are plenty of reason for the exception No suitable driver found for jdbc:mysql like
Your JDBC URL can be wrong.
ClassPath/BuildPath/Lib folder missing the connector jar.
Driver Information is Wrong.
Just load the driver first:
Class.forName("com.mysql.jdbc.driver");

What might be wrong with this JSP

conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ebookshop", "root", "");
XAMPP is hosting MySQL on 3306
I linked the mysql connect jar
ebookshop is the name of a DB
http://i.imgur.com/9XJjLiX.png
I have a user root wit no password
But I am getting a
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/ebookshop
...
I have run other JSP and it works, I have a print statement just before the conn statement and it prints, one after that does not.
Thank you
You need to add the MySQL JDBC driver to your app's classpath. The most straight forward way to do that if you're running in a servlet container such as Tomcat or Jetty, would be to place the driver jar file in your app's WEB-INF/lib folder.
Try this code :-
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e)
{
System.out.println("Error in Data base Driver:"+e);
}
try
{
String url="jdbc:mysql://localhost:3306/ebookshop", "root", "";
connection=DriverManager.getConnection(url,userName,pass);
}
catch (Exception e)
{
System.out.println("Error in database connection:"+e);
}
First register your driver. Then you can use the url.

How to create a JDBC MySQL connection pool in Tomcat7 installed on Amazon EC2?

I am new and any help will be highly appreciated. I have a Webapp installed on Amazon EC2. I have installed Tomcat7 and MySQL 5.5 on Amazon EC2.
I am using following code in servlet for JDBC-MySQL connection
Connection connection;
Statement statement;
ResultSet rs = null;
try {
// load Connector/J
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(JDBC_MYSQL_STRING);
System.out.println(TAG + " Connection with MySQL established");
statement = connection.createStatement();
....
....
....
rs.close();
statement.close();
connection.close();
} catch (ClassNotFoundException ex) {
Log.log(Level.SEVERE, "ClassNotFoundException", ex);
} catch (SQLException e) {
for (Throwable t : e) {
System.out.println(t.getMessage());
}
I have included mysql-connector-java-5.1.13-bin.jar for Connector/J in the Library folder for Netabeans and deployed war files on tomcat7 in Amazon ec2.
My Question
I have learned that JDBC-MySQL connection is very time consuming operation and connection pools can be used to keep live connection which will reduce time consumed in connection. I am new to this and have read my blogs but unable to understand how to set up connection pool and how to use it in the servlets?
Thanks.
You need to setup the DB Connection in server.xml
Follow this:
http://www.mulesoft.com/tomcat-mysql
The URL of your database would take this form:
"jdbc:mysql://yourdatabasename.foo.us-east-1.rds.amazonaws.com:3306/"

Tomcat 7: How do I specify Database resource when making connection to Microsoft Access

I know how to specific datasource connection pooling to a mysql server in Tomcat 7, add
<Resource type="javax.sql.DataSource"
name="jdbc/TestDB"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql"
username="mysql_user"
password="mypassword123"
/>
to my META-INF/context.xml,
Can anyone show me how to do this to Microsoft Access?
Do I need a JDBC - ODBC bridge to make connection from my Java web app to Microsoft Access?
UPDATE: This is my attempt, but I ran into SQLException
<Resource type="javax.sql.DataSource"
name="jdbc-odbc/qtl"
maxActive="100"
maxIdle="30"
maxWait="10000"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
driverClassName="sun.jdbc.odbc.JdbcOdbcDriver"
url="jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=/Users/KingdomHeart/resources/db.mdb"
/>
When I do this, I got WARNING: Unexpected exception resolving reference
java.sql.SQLException: sun.jdbc.odbc.JdbcOdbcDriver
UPDATE 2:: I tried to write a separate program in effort to make connection to Microsoft Access db. I got java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Here is my code. It must be that I need a jar driver in my class path, do I not?
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String fileName = "/Users/KingdomHeart/resources/MyTable.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database += fileName + ";DriverID=22;READONLY=true";
Connection con = DriverManager.getConnection(database, "", "");
System.out.println("here");
} catch (SQLException ex) {
Logger.getLogger(TestJdbcOdbc.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(TestJdbcOdbc.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'd use a URL like this:
jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\path\\your-access-database.mdb
The JDBC driver class is sun.jdbc.odbc.JdbcOdbcDriver (at least it was when I last used it; that was back in 2004).
I prefer this style because it eliminates the step of creating an ODBC data source. It keeps the precise location of the file inside the Java deployment.
Yes, you need the JDBC-ODBC bridge (unless you bought a commercial JDBC driver).
You should be aware of the pitfalls of using Access in a multi-user environment:
http://msdn.microsoft.com/en-us/library/aa167840(v=office.11).aspx
My personal recommendation would be to use MySQL or PostgreSQL instead of Access.
Here's something else you might want to read about setting up a JNDI data source on Tomcat:
http://craicpropagation.blogspot.com/2009/02/how-to-use-same-jndi-resource-name-on.html

Categories

Resources