I'm trying to run the following code but It always results in a "http 500 Internal Server Error"
Could someone help me debug this error
I just started learning Servlets and JSP..So please excuse me if I miss any details in the question. Looking in the MYSQL database error logs, I found the following entries:
Aborted connection 44 to db: 'sakila' user: 'root' host: 'localhost' (Got an error reading communication packets)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
final String DB_URL="jdbc:mysql://localhost:3306/sakila";
final String user="root";
final String password="pass1234";
Statement stmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
out.println("Cannot load driver");
}
Connection conn=null;
try {
conn=DriverManager.getConnection(DB_URL,user,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
out.println("Cannot Connect to Database");
}
//out.print("Connected to Database");
out.println("<html>");
out.println("<body>");
String str= "SELECT actor_id, first_name last_name FROM temp where actor_id='1';";
try {
ResultSet rs=stmt.executeQuery(str);
while(rs.next()){
out.println(rs.getString("actor_id"));
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
try {
ResultSet rs;
rs = stmt.executeQuery(str);
while(rs.next()){
int i=rs.getInt("actor_id");
String fn= rs.getString("first_name");
String ln=rs.getString("last_name");
out.print(i+"::");
out.print(fn+"::");
out.print(ln+"::");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
out.print("hkshfdkhfakfshdkha");
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("</body>");
out.println("</html>");
}
Aborted connection 44 to db: 'sakila' user: 'root' host: 'localhost'
(Got an error reading communication packets)
This error trace is appearing in your console because you are trying to making new db connection to the mysql database on every doGet() request without properly closing your db connection.
And thats why whenever a communication error occurs it increments the status counter for either Aborted_clients or Aborted_connects, which describe the number of connections that were aborted because the client died without closing the connection properly and the number of failed attempts to connect to MySQL server (respectively).
Out of the various reasons causing this issue, here are few important ones that you might want to check.
The client connected successfully but terminated improperly (and may
relate to not closing the connection properly)
The client slept for longer than the defined wait_timeout or
interactive_timeout seconds (which ends up causing the connection to
sleep for wait_timeout seconds and then the connection gets forcibly
closed by the MySQL server)
The client terminated abnormally or exceeded the max_allowed_packet
for queries
So as right mentioned by #Matt Clark you should be going for a connection pool mechanism to avoid this issue and also to follow best pratices around interfacing with databases.
If you check your application logs, it is my assumption that you will see the stacktrace generated by
e1.printStackTrace();
This is because you have an error in you SQL syntax.
SELECT actor_id, first_name last_name FROM temp where actor_id='1';
/\ add missing comma
On a side note - you should not be establishing the connection to the databse inside each request. This slows everything down.
Instead, you should be using a connection pool, I recommend C3P0.
The reason for abrupt termination in your database logs, is because your application throws an exception and abandons the connection without properly closing it.
Related
I am using spring jdbc. How can I get the current Connection object for an Oracle database? I'm using connection pooling with JBOSS Wildfly server. I am getting the connection url in my DaoImp by using this code:
Connection con;
try {
con = getJdbcTemplate().getDataSource().getConnection();
dataSource.getConnection().getMetaData().getURL();
connectionUrl = con.getMetaData().getURL();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If I write the same code in the setJdbcTemplate method then I am not getting connections over there.There error as follows
No managed connections available within configured blocking timeout (0
[ms])
my setJdbcTemplate method as follwos
public void setDataSource(DataSource dataSource){
this.dataSource = dataSource;
setJdbcTemplate(new JdbcTemplate(this.dataSource));
setNamedParamdbcTemplate(new NamedParameterJdbcTemplate(this.dataSource));
if(connectionUrl==null){
Connection con;
try {
con = getJdbcTemplate().getDataSource().getConnection();
connectionUrl = con.getMetaData().getURL();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try increase blocking timeout in ds.xml file. see configure data source in JBOSS
blocking-timeout-millis : This element specifies the maximum time in
milliseconds to block while waiting for a connection before throwing
an exception. Note that this blocks only while waiting for a permit
for a connection, and will never throw an exception if creating a new
connection takes an inordinately long time. The default is 5000.
Default values
- the length of time to wait for a
connection to become available when all the connections are checked
out (default 5000 == 5 seconds, from 3.2.4 it is 30000 == 30 seconds)
<blocking-timeout-millis>5000</blocking-timeout-millis>
You can specify the max and min connection pool size in the -ds.xml file.
<!--pooling parameters-->
<min-pool-size>5</min-pool-size>
<max-pool-size>100</max-pool-size>
<blocking-timeout-millis>5000</blocking-timeout-millis>
I managed to setup a client and server connection using Java socket. After checking the connection had been establish, I tried sending Protocol commands that are provided by the SDK from the server and I'm using a JButton to execute the commands.
Examples of the commands are play, stop and ping the server.
The code below shows how I setup the connection and send the protocol commands
public void socket1()
{
Socket MyClient;
try {
MyClient = new Socket("192.168.10.61",9993);
os = new DataOutputStream(MyClient.getOutputStream());
is = new DataInputStream(MyClient.getInputStream());
lblerror.setText("Connected");
MyClient.getOutputStream().write("play".getBytes("US-ASCII"));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
lblerror.setText("Don't know about host: hostname");
} catch (IOException e) {
// TODO Auto-generated catch block
lblerror.setText("Couldn't get I/O for the connection to: hostname");
}
}
After pressing the button on the GUI, The server did not response to the command 'play' and there is no error.
As Scarry Wombat wrote, use os.write()
But instead of .write() use .writeBytes(),
because you want to send a byte array(?). Alternatively you could send a String with UTF-encoding by using .writeUTF()
I am trying to connect to my website's MySQL database, and I have no knowledge of PHP so I decided to use JDBC. I followed some video tutorials (non JDBC) and I used their steps. I skipped the MAMP step though because I am not hosting the server off of my PC. It is being hosted locally because it is going to be a larger website.
So I have this code entered in my Login Activity (first screen you see):
Connection connection = null;
Statement statement = null;
String username = "username";
String password = "password";
String dbURL = "jdbc:mysql://216.26.176.52:3306/lifesizefoto";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(dbURL, username, password);
statement = connection.createStatement();
System.out.println("Connected.");
} catch (ClassNotFoundException error) {
System.out.println("Cannot connect");
} catch (SQLException error) {
System.out.println("Error: " + error.getMessage());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) { try {connection.close();} catch (SQLException ignore) {} }
if (statement != null) { try {statement.close();} catch (SQLException ignore) {} }
}
I have tried many variations to the .getConnection() statement, but I can't figure it out. I have also contacted the website host and he took down all firewalls for my IP and even opened up a special port for the app.
When I run my app, I get this error:
01-09 18:59:32.769: I/System.out(14178): Error: Communications link failure
01-09 18:59:32.769: I/System.out(14178): The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I would appreciate any help. Thank you in advanced!
Two thoughts:
It's unlikely that your web site's MySQL server is bound to an external interface - it's likely only listening on the localhost interface. Your hosting provider should be able to confirm / possibly fix that for you.
Trying to connect a mobile app directly to a server database is probably not going to work well in the long run - I'd suggest that you either figure out how to write a server-side app (for your mobile app to connect to) in PHP, or find another language that your host supports, and do it in that.
Hi I'm trying to clean up my code to remove errors stating that my db connection was opened but not closed correctly.
If I have a db.open() then a few try catch statements around db query's then a db.close() following the try catch will it use the same db connection within the try catches or does java discretely run the try catch statements so the db connection is not available.
In short, should i have code something like this:
db.open();
try {
// here
db.getThings()
} catch () {
// there
}
try {
// here 2
db.getMoreThings()
} catch () {
// there 2
}
db.close();
Or this:
try {
// here
db.open();
db.getThings()
db.close();
} catch () {
// there
}
try {
// here 2
db.open();
db.getMoreThings()
db.close();
} catch () {
// there 2
}
I'd have thought the first solution of opening one db connection is the better one. But i'm running into issues with not closing db connections and i'm at the point of thinking there's a fundamental issue with my design.
I've also tried opening the connection in onResume() then close in onPause() but still having problems.
There is a recommendation to close DB connection as soon as you selected data, so in my app I mainly use the following template:
db.open();
try {
// select data
} finally {
db.close();
}
it worked for me.
I am attempting to use a pooled connection for my web application in Java. I am using an Oracle database and here is my code:
public class DatabaseHandler
{
static private Connection m_database = null;
static private OracleConnectionPoolDataSource pooledSource = null;
/**
* Attempts to open an Oracle database located at the specified serverName and port.
* #param serverName Address of the server.
* #param portNumber Port to connect to.
* #param sid SID of the server.
* #param userName Username to login with.
* #param password Password to login with.
* #throws WebApplicationException with response code 500 Internal Server Error.
*/
static public void openDatabase(String userName, String password,String serverName,int portNumber, String sid)
throws WebApplicationException
{
try
{
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
// Create a connection to the database
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + sid;
pooledSource = new OracleConnectionPoolDataSource();
pooledSource.setUser(userName);
pooledSource.setURL(url);
pooledSource.setPassword(password);
m_database = pooledSource.getConnection();
}
catch (ClassNotFoundException e)
{
// Could not find the database driver
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
catch (SQLException e)
{
// Could not connect to the database
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
/**
* Attempts to execute the specified SQL query.
* #throws WebApplicationException with a response code of Bad Request
* if the query is invalid SQL.
*/
static public ResultSet makeQuery(String query) throws WebApplicationException
{
ResultSet rs = null;
if (m_database != null)
{
try
{
Statement stmt = m_database.createStatement();
rs = stmt.executeQuery(query);
}
catch (SQLException e)
{
// invalid query
System.out.println(query);
throw new WebApplicationException(Response.Status.BAD_REQUEST);
}
}
return rs;
}
/**
* Attempts to close the database.
* #throws WebApplicationException with a response code of 500 Server error
*/
static public void closeDatbase() throws WebApplicationException
{
try
{
m_database.close();
pooledSource.close();
}
catch(SQLException e)
{
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
}
}
I am doing this in Eclipse and I have a warning that pooledSource.close() is deprecated. I have never used a pooled connection before and I just want to be sure that I am doing everything correctly. Is there a better way to close an Oracle pooled resource?
A deprecated method means that this method shouldn't be used. In future releases, the close() method can be purged entirely. I suggest removing pooledSource.close().
Also, I would suggest not to have a static instance of a Connection and DataSource as you require a connection on request and not keep it alive throughout the application. Always close a ResultSet first and then a Connection and guarantee the closure by adding them in a finally block.
The connection must be closed to be returned to the pool.
Always close your connection in a finally-block.
Never hold connection references as a class member - this is error prone and bad design. Connections should be aquired as late as possible and released as soon as possible. It does not make sense to hold something like that as class member.
Close connections where they are used. Your code is error prone again here. If you forget to call closeDatabase() you're leaking connections.
Attention:
Do not jumble closing the connection and closing the connection pool here.
Because it was requested here's some code for correct and good connection handling:
public void doSomethingWithDb(Connection con, ...) {
boolean release = (con == null);
try {
con = PersistenceUtils.getConnection(con); //static helper return a new conenction from pool when provided con==null otherwise simply returns the given con
//do something
if(release) {
con.commit();
}
}
catch(SQLException e) {
//handle errors, i.e. calling con.rollback() but be sure to check for con!=null before. Again maybe null-safe static helper method here.
}
finally {
if(release && con!=null){
con.close();
}
}
}
I am using Connection as method parameter in order to be able to call many of such methods in one db transaction. But you can always put null as first argument for Connection and the method get a connection from pool for you.
When you call another "DB-Method" inside a "DB-Method" you just provide your connection to the underlying method - so you have everything in one transaction then.
As you see correct JDBC code produces much boilerplate code. In the first step you can reduce it by implementing a Utility-Class like PersistenceUtils which provides static null-safe methods like commit(Connection), rollback(Connection), getConnection(Connection), close(Connection) ...
With that you get rid of all null-checks and you can include logging or something else there, too.