unable to connect to Azure SQL database from Jsp - java

I'm new to MS Azure and I'm trying to connect to the SQL database in Azure using the following code.
When i publish this same code and try to access it in Azure I'm getting 404 error.
Also, if I this same code to connect it from local server, connection gets refused.
I have attached error along with this question.
Can anyone help me?
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%#page import="java.sql.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DB connection</title>
</head>
<body>
<h1>Azure DB connection</h1>
<%
final String DB_URL =
"jdbc:jtds:sqlserver://pkynvzyf2a.database.windows.net/nj-javapocdb";
// Database credentials
final String USER = "Username";
final String PASS = "Password";
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "SELECT StudentID, FirstName, LastName FROM
StudentDetails";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
Integer id = rs.getInt("StudentID");
String last = rs.getString("LastName");
String first = rs.getString("FirstName");
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
%>
</body>
</html>
Error in local:
Connecting to database...
java.sql.SQLException: Network error IOException: Connection refused:
connect
Goodbye!
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:436)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:141)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service
(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke
(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke
(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke
(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke
(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke
(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke
(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke
(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service
(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process
(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process
(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun
(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run
(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at net.sourceforge.jtds.jdbc.SharedSocket.createSocketForJDBC3
(SharedSocket.java:288)
at net.sourceforge.jtds.jdbc.SharedSocket.<init>(SharedSocket.java:251)
at net.sourceforge.jtds.jdbc.JtdsConnection.<init>(JtdsConnection.java:331)
... 31 more
error in azure

All services in Azure are locked down and secure by default. Therefore, you need to allow access to the SQL Azure instance.
If you are running from your local machine, then you external IP address most be whitelisted.
If you are using Azure Websites/App Services you need to allow them to access also.
See how-to configure firewall settings for an Azure SQL database instance.

Related

Failed to connect MySQL in IDEA 12.1.4

I had learn javascript on the base of code of my web. Then, I tried to develop a new web but failed. After google, I still don't have clues. So I ask for help here. Thanks for advance.
My IDEA is 12.1.4. The install process is:
1) I make new project by selecting "JavaEE Web Module";
2) I then copy previously java script to deal with mysql, and a part of code would be listed below;
package inhouse;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
public class DBTool {
private DataSource ds = null;
private Connection conn = null;
private Statement stm = null;
private ResultSet rs = null;
private Context ctx = null;
public DBTool() throws NamingException{
this("editingphosphorylation");
}
public DBTool(String dbName) throws NamingException{
try{
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/" + dbName);
}
catch (NamingException e) {
throw new NamingException("Can't get DataSource from pool: " + e.getMessage());
}
}
public Connection getConnection() throws SQLException{
conn = ds.getConnection();
return conn;
}
......
}
3) Add "resource-ref" to WEB-INF/web.xml;
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/editingphosphorylation</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4) Download "mysql-connector-java-5.1.40-bin.jar", and put it to WEB-INF/lib;
5) With "View-Tool Windows-Database", I confirm mysql database could be accessed;
6) But when start tomcat, it output following error:
HTTP Status 500 - An exception occurred processing JSP page /geneList.jsp at line 26
type Exception report
message An exception occurred processing JSP page /geneList.jsp at line 26
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /geneList.jsp at line 26
23:
24: try{
25: db = new DBTool();
26: conn = db.getConnection();
27: //Class.forName("com.mysql.jdbc.Driver").newInstance();
28: //Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
29: pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:455)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:916)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:845)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:147)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:524)
sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:493)
sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307)
java.sql.DriverManager.getDriver(DriverManager.java:262)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
inhouse.DBTool.getConnection(DBTool.java:39)
org.apache.jsp.geneList_jsp._jspService(geneList_jsp.java:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Any geneList.jsp is like this
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="inhouse.*, java.sql.*" %>
<%# page import="java.io.*" %>
<html>
<head>
<title>get gene list</title>
</head>
<body>
<% String geneName = request.getParameter("geneName");
DBTool db;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
db = new DBTool();
conn = db.getConnection();
//Class.forName("com.mysql.jdbc.Driver").newInstance();
//Connection conn = java.sql.DriverManager.getConnection("jdbc:mysql://localhost:3306/editingphosphorylation","2pm","editingphosphorylation");
pst = conn.prepareStatement("select * from gene_sequence where geneName = ?");
pst.setString(1, geneName);
rs = pst.executeQuery();
if(rs.next()){
rs.beforeFirst();%>
<table>
<th>
<td>Gene Name</td><td>Transcript Name</td><td>DNA Sequence</td><td>Protein Sequence</td>
</th>
<%while(rs.next()){
String geneNameRetrieve = rs.getString("geneName");
String transcriptNameRetrieve = rs.getString("transcriptName");
String dnaSequenceRetrieve = rs.getString("dnaSequence");
String proteinSequenceRetrieve = rs.getString("proteinSequence"); %>
<tr>
<td><%=geneNameRetrieve%></td><td><%=transcriptNameRetrieve%></td><td><%=dnaSequenceRetrieve%></td><td><%=proteinSequenceRetrieve%></td>
</tr><%
}%>
</table>
<%}else{%>
<div>No data.</div>
<%}
DBTool.close(rs, pst);
}finally {
DBTool.close(conn);
}%>
</body>
</html>
Compare with previously project, and according to google, I found the new project lack META-INF directory, so I make a new directory in web, and put a new context.xml into it.
<?xml version='1.0' encoding='utf-8'?>
<Context path="/">
<Loader delegate="true" />
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="jdbc/editingprosphorylation" auth="Container" type="javax.sql.DataSource"
maxActive="555" maxIdle="50" maxWait="10000"
timeBetweenEvictionRunsMillis="60000"
username="2pm" password="editingprosphorylation" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/editingprosphorylation"/>
</Context>
However, it doesn't work. After google, I hardly don't know how to do, Any suggestion would be grateful!
Typo:
editingphosphorylation (editingpHosphorylation)
editingprosphorylation (editingpRosphorylation)

Unable to connect to sql server using java 8

I'm trying to connect to my sql server 21014 using java 8. But i'm getting error.
import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class DBConnec
{
public static void main(String a[])
{
try
{
String url = "jdbc:jtds:sqlserver//localhost:1433/dictionary";
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(url);
System.out.println("connection created");
Statement st=conn.createStatement();
String sql="select * from data where word LIKE 'hi'";
ResultSet rs=st.executeQuery(sql);
if (rs.next())
{
System.out.println(rs.getString(0));
}
if(st!=null)
st.close();
if(conn!=null)
conn.close();
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Exception i'm getting is:
java.sql.SQLException: The syntax of the connection URL 'jdbc:jtds:sqlserver//localhost:1433/dictionary' is invalid.
at net.sourceforge.jtds.jdbc.Driver.setupConnectProperties(Driver.java:241)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:181)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnec.main(DBConnec.java:15)
I'm running my code using this command:
java -cp .;"C:\Program Files\Java\jdk1.8.0_66\jre\lib\ext\jtds-1.3.0.jar" DBConnec
I've also tried url without writing "sqlserver". But it gives same exception.
Please help.. Thank you..
I've corrected my syntax but now i'm getting exception like this:
java.sql.SQLException: Network error IOException: Connection refused: connect
at net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:434)
at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:183)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnec.main(DBConnec.java:15)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
Try this:
String url = "jdbc:jtds:sqlserver://localhost:1433/dictionary";
You missed the colon after sqlserver.
You should not be adding JDBC driver JARs to the jre/lib/ext directory. Learn how to use CLASSPATH properly.
The url format for JTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So your url should be like:
String url = "jdbc:jtds:sqlserver://localhost:1433/dictionary";
^^^____missing colon

Connect MySql (CPanel) remotely via JAVA

=================Code===================
package com.name.file;
import java.sql.*;
public class JDBC {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://162.219.26.220:3306/waseianc_db";
// Database credentials
static final String USER = "waseianc_vinit";
static final String PASS = "pass";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
// Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
======================Errors========================
Connecting to database...
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Last packet sent to the server was 2 ms ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2104)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.name.file.JDBC.main(JDBC.java:24)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:276)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2027)
... 12 more
=============================== Cpanel Remote Access ====================
=========================== Cpanel MySQL DataBase =========================
Yes, Please contact your hosting provider and ask them to enable mysql port 3306 in firewall and try to login again.

Connect Servlet to MySQL database in eclipse [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 6 years ago.
I successfully connected database with simple java program using JDBC but when I am trying to connect database with Servlet, it gives me following errors and exceptions:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8888/ebookshop
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at QueryServlet.doGet(QueryServlet.java:35)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
All severs running well and also I already added servlet and connecter API's in my library.
For more Information these are my html and servlet files are:
html file
<html>
<head><title>Yet Another Bookshop</title></head>
<body>
<h2>Yet Another Bookshop</h2>
<form method="get" action="http://localhost:9999/Sixth/query">
<b>Choose an author:</b>
<input type="checkbox" name="author" value="Tan Ah Teck">Ah Teck
<input type="checkbox" name="author" value="Mohammad Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Search">
</form>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class QueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// JDK 6 and above only
// The doGet() runs once per HTTP GET request to this servlet.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set the MIME type for the response message
response.setContentType("text/html");
// Get a output writer to write the response message into the network socket
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
// Step 1: Allocate a database Connection object
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
// Step 3: Execute a SQL SELECT query
String sqlStr = "select * from books where author = "
+ "'" + request.getParameter("author") + "'"
+ " and qty > 0 order by price desc";
// Print an HTML page as the output of the query
out.println("<html><head><title>Query Response</title></head><body>");
out.println("<h3>Thank you for your query.</h3>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
// Step 4: Process the query result set
int count = 0;
while (rset.next()) {
// Print a paragraph <p>...</p> for each record
out.println("<p>" + rset.getString("author")
+ ", " + rset.getString("title")
+ ", $" + rset.getDouble("price") + "</p>");
count++;
}
out.println("<p>==== " + count + " records found =====</p>");
out.println("</body></html>");
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You need to load your driver before you get a connection, something like that:
//Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
Here is a nice example: http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm
you should add this line,
Class.forName("com.mysql.jdbc.Driver");
As it is the first step to establish connection with JDBC driver,
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 1: Allocate a database Connection object
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:8888/ebookshop", "myuser", "xxxx"); // <== Check!
// database-URL(hostname, port, default database), username, password
// Step 2: Allocate a Statement object within the Connection
stmt = conn.createStatement();
Provide that you added the mysql connector jar in your buidpath
As I see this jdbc:mysql://localhost:8888/ebookshop you have changed the default port of mysql from 3306 to 8888
If you did not change the port just use 3306 as the port for mysql
As the exception is saying No suitable driver found that obviously means you don't have the
mysql-connector-[version].jar in your classpath If you are using eclipse just place the jar under WEB-INF/lib and if you are using standalone tomcat just place the driver jar in the lib folder of Tomcat
try this
public static void connect() throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/database_name?autoReconnect=true";
c = DriverManager.getConnection(url,"root","123");
}
thanx..

How to connect JAVA to SQL Server 2012?

Hey friends I am totally new in JAVA and i want to now how to connect JDBC with SQL Server 2012. I go through so much material but i didn't get it. So can you give me a sample demo code...
I have one more problem that i installed SQL Server 2012 but i don't know what is username, password and server name. SO what can i do for it??
When i code it gives error...
Code:
import java.sql.*;
public class Conection
{
public static void main(String a[]) throws ClassNotFoundException, SQLException
{
try
{
String url = "jdbc:sqlserver://localhost:1433//SQLEXPRESS;databaseName=mydb";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
System.out.println("connection created");
Statement st=conn.createStatement();
String sql="select * from mydb";
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
System.out.println("Name: "+rs.getString(1));
//System.out.println("Address : "+rs.getString(2));
}
if(st!=null)
st.close();
if(conn!=null)
conn.close();
}
catch(SQLException sqle)
{
System.out.println("Sql exception "+sqle);
}
}
}
Error
Exception in thread "main" java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Conection.main(Conection.java:11)
It seems your sql driver classes is not in classpath. if your are using an IDE add it to classpath else add it manually before compiling your class.

Categories

Resources