Java - JDBC driver and MySQL database connection issues - java

Ok - I found the driver version that goes with the database.. however now I get the following.
Got an exception! Communications link
failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException MESSAGE:
Connection timed out: connect
STACKTRACE:
java.net.ConnectException: Connection
timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native
Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at java.net.Socket.connect(Socket.java:475)
at java.net.Socket.(Socket.java:372)
at java.net.Socket.(Socket.java:215)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at freelancebillingapp.customerInfoUI.jButton1MouseClicked(customerInfoUI.java:221)
at freelancebillingapp.customerInfoUI.access$000(customerInfoUI.java:12)
at freelancebillingapp.customerInfoUI$1.mouseClicked(customerInfoUI.java:59)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:253)
at java.awt.Component.processMouseEvent(Component.java:6266)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3255)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4247)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
** END NESTED EXCEPTION **
Last packet sent to the server was 1
ms ago.

This may not solve it, but it tells you that someone else has had this problem.
Make sure you have the precise version of JDBC driver to match your version of MySQL.
I would strongly urge you to rewrite your code more like this. You aren't closing resources properly at all.
Adapt it to your own needs. I created a local MySQL database on my machine and added a customer table. It worked just fine.
package persistence;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class DatabaseUtils
{
private static final String URL = "jdbc:mysql://localhost:3306/contacts";
private static final String USERNAME = "contacts";
private static final String PASSWORD = "contacts";
public static final String SELECT_SQL = "select customer_id, name, street, city, state, zip, phone, url from customer order by customer_id";
public static final String INSERT_SQL = "insert into customer(name, street, city, state, zip, phone, url) values(?,?,?,?,?,?,?)";
public static void main(String[] args)
{
Connection connection = null;
try
{
connection = getConnection(URL, USERNAME, PASSWORD);
List<Map> rows = findAllCustomers(connection);
for (Map row : rows)
{
System.out.println(row);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
close(connection);
}
}
public static List<Map> findAllCustomers(Connection connection) throws SQLException
{
List<Map> rows = new ArrayList<Map>();
PreparedStatement st = null;
ResultSet rs = null;
try
{
st = connection.prepareStatement(SELECT_SQL);
rs = st.executeQuery();
while (rs.next())
{
rows.add(map(rs));
}
}
finally
{
close(rs);
close(st);
}
return rows;
}
private static Map<String, Object> map(ResultSet rs) throws SQLException
{
Map<String, Object> row = new LinkedHashMap<String, Object>();
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
for (int i = 1; i <= numColumns; ++i)
{
String column = meta.getColumnName(i);
Object value = rs.getObject(i);
row.put(column, value);
}
return row;
}
public static Connection getConnection(String url, String username, String password) throws SQLException
{
Driver driver = DriverManager.getDriver(url);
DriverManager.registerDriver(driver);
return DriverManager.getConnection(url, username, password);
}
public static void close(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(Statement st)
{
try
{
if (st != null)
{
st.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void close(ResultSet rs)
{
try
{
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void rollback(Connection connection)
{
try
{
if (connection != null)
{
connection.rollback();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}

Can mysql accept network connections? When you connect with the "mysql" command line program, you're not doing a network connection, but when you do with JDBC you are making a network connection. Try using "-h localhost" in your mysql command line to see.

/*
Connection
*/
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
public class PersonalConnection {
private String url = "jdbc:mysql://localhost:3306/";
private String schema = "database name";
private String uname = "";
private String password = "";
private Connection connection;
public Connection openConnection() {
try {
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
} catch (Exception ex) {
}
connection = (Connection) DriverManager.getConnection(url + schema, uname, password);
} catch (Exception ex) {
}
return connection;
}
public void closeConneciton() {
try {
connection.close();
} catch (Exception ex) {
}
}
}
/* Servlet */
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
DetailsBean db = new DetailsBean();
String name = request.getParameter("name");
String countryname = request.getParameter("countryname");
String statename = request.getParameter("statename");
db.setName(name);
db.setCountry(countryname);
db.setState(statename);
DetailsManager dm = new DetailsManager();
String result = dm.insertDetailsManager(db);
if (result.equals("true")) {
/* RequestDispatcher rd = request.getRequestDispatcher("StateDetails.jsp?name=" + db.getName());
rd.forward(request, response);*/
response.sendRedirect("StateDetails.jsp");
} else {
out.print(result);
}
/* DAO */
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import com.mysql.jdbc.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DetailsDAO {
private Connection connection;
private PersonalConnection con;
public DetailsDAO() {
con = new PersonalConnection();
}
public String insertRecordDAO(DetailsBean db) {
int rowcount=0;
try {
connection=con.openConnection();
String query = "INSERT INTO personal_details(user_name,country_name,state_name) values(?,?,?);";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, db.getName());
ps.setString(2, db.getCountry());
ps.setString(3, db.getState());
rowcount = ps.executeUpdate();
if(rowcount==1)
{
return "true";
}
else
{
return "false";
}
} catch (Exception ex) {
return ex+"";
} finally {
con.closeConneciton();
}
}
public ResultSet getGetails() throws Exception
{
connection=con.openConnection();
String query="SELECT * from state_details";
PreparedStatement ps=connection.prepareStatement(query);
ResultSet rs=ps.executeQuery();
return rs;
}
}
/*Manager*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.util.ArrayList;
public class DetailsManager {
DetailsDAO detdao = new DetailsDAO();
public String insertDetailsManager(DetailsBean db) {
String rowcount = detdao.insertRecordDAO(db);
return rowcount;
}
}
/*Bean*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
public class DetailsBean {
private String name;
private String country;
private String state;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}

Related

Is it possible to reuse a connection statement without closing it? [duplicate]

I've been working at this for almost a day and a half now and I can't seem to work this error out. I don't know why the ResultSet is being closed. Maybe some of you can help me out.
MySQLDatabase:
package net.gielinor.network.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public abstract class MySQLDatabase {
private String host;
private String database;
private String username;
private String password;
private Connection connection = null;
private Statement statement;
public MySQLDatabase(String host, String database, String username, String password) {
this.host = host;
this.database = database;
this.username = username;
this.password = password;
}
public abstract void cycle() throws SQLException;
public abstract void ping();
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(String.format("jdbc:mysql://%s/%s", host, database), username, password);
statement = connection.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
public void ping(String table, String variable) {
try {
statement.executeQuery(String.format("SELECT * FROM `%s` WHERE `%s` = 'null'", table, variable));
} catch (Exception e) {
connect();
}
}
public ResultSet query(String query) throws SQLException {
if (query.toLowerCase().startsWith("select")) {
return statement.executeQuery(query);
} else {
statement.executeUpdate(query);
}
return null;
}
public Connection getConnection() {
return connection;
}
}
MySQLHandler
package net.gielinor.network.sql;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import net.gielinor.network.sql.impl.MySQLDonation;
public class MySQLHandler extends Thread {
private static final MySQLHandler mysqlHandler = new MySQLHandler();
public static MySQLHandler getMySQLHandler() {
return mysqlHandler;
}
private static List<MySQLDatabase> updateList;
private static String host;
private static String database;
private static String username;
private static String password;
#Override
public void run() {
while (true) {
for (MySQLDatabase database : updateList) {
try {
if (database.getConnection() == null) {
database.connect();
} else {
database.ping();
}
database.cycle();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
Thread.sleep(10000);
} catch (Exception ex) {
}
}
}
}
private static void loadProperties() {
Properties p = new Properties();
try {
p.load(new FileInputStream("./sql.ini"));
host = p.getProperty("host");
database = p.getProperty("database");
username = p.getProperty("username");
password = p.getProperty("password");
} catch (Exception ex) {
System.out.println("Error loading MySQL properties.");
}
}
public static String getHost() {
return host;
}
static {
loadProperties();
updateList = new ArrayList<MySQLDatabase>();
updateList.add(new MySQLDonation(host, database, username, password));
}
}
MySQLDonation
package net.gielinor.network.sql.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import net.gielinor.game.model.player.Client;
import net.gielinor.game.model.player.PlayerHandler;
import net.gielinor.game.model.player.PlayerSave;
import net.gielinor.network.sql.MySQLDatabase;
public final class MySQLDonation extends MySQLDatabase {
public MySQLDonation(String host, String database, String username, String password) {
super(host, database, username, password);
}
#Override
public void cycle() throws SQLException {
ResultSet results = query("SELECT * FROM `gieli436_purchases`.`donations`");
if (results == null) {
return;
}
while (results.next()) {
String username = results.getString("username").replace("_", " ");
System.out.println("name=" + username);
Client client = (Client) PlayerHandler.getPlayer(username.toLowerCase());
System.out.println(client == null);
if (client != null && !client.disconnected) {
int creditamount = results.getInt("creditamount");
if (creditamount <= 0) {
continue;
}
handleDonation(client, creditamount);
query(String.format("DELETE FROM `gieli436_purchases`.`donations` WHERE `donations`.`username`='%s' LIMIT 1", client.playerName.replaceAll(" ", "_")));
}
}
}
#Override
public void ping() {
super.ping("donations", "username");
}
private void handleDonation(Client client, int creditamount) throws SQLException {
client.credits = (client.credits + creditamount);
client.sendMessage("Thank you for your purchase. You have received " + creditamount + " store credits.");
PlayerSave.save(client);
}
}
The exception occurs here: in the while loop within MySQLDonation and the actual stacktrace is this:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7077)
at net.gielinor.network.sql.impl.MySQLDonation.cycle(Unknown Source)
at net.gielinor.network.sql.MySQLHandler.run(Unknown Source)
With this information let me say that this does work, I get my message and what not in-game but it repeats, like the user is never removed from the query so it gives them infinite rewards. If you need any more information feel free to ask.
When you run the Delete query, you use the same Statement that was used in the Select query. When you re-execute on the same Statement, the previous ResultSet gets closed.
To avoid this, you should create a new Statement everytime you execute a query. So remove statement = connection.createStatement(); from the connect() method in MySQLDatabase class, and replace all statement in that class to connection.createStatement(). You may also choose to delete the private variable statement altogether.
You can read more about it here.
this error is some time occur when we use same statement object for diff. types
check Statement objectsss;

How to get the list of all database names from a Sybase DB Server in java

I want to get the list of all database names from a Sybase DB server. I can connect the Sybase db through Java, but don't know how to get the list of database names. I am using jconn4 jar file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}
I found myself a working code.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.SybDriver;
public class ConnectToSybase {
public static Connection conn = null;
public static Statement stmt = null;
public static SybDriver sybDriver = null;
public static ResultSet rs = null;
public static String dbServerIP = "10.10.10.11";
public static String portNo = "5000";
public static String dbName = "NewDB";
public static void main(String[] args) {
try {
Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
System.out.println("Driver loaded");
conn = DriverManager.getConnection("jdbc:sybase:Tds:" + dbServerIP + ":" + portNo, "usrname", "password");
stmt = conn.createStatement();
List<String> dbList = new ArrayList<String>();
// getting list of DB names from the DB server
ResultSet rs = conn.getMetaData().getCatalogs();
while (rs.next()) {
dbList.add(rs.getString(1));
}
for (String list : dbList) {
System.out.println(list);
}
} catch (Exception e) {
System.out.println("In exception");
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}
}

Class Not found exception in servlet connecting mysql

I was trying to connect mysql database in my servlet. Then I'm getting an exception.But when I am testing the database connection from a usual Java class the connection is ok and I getting the data from the database.The exception I'm getting on tomcat server console is:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver .
The code of my DatabaseHandler.java is:
import java.sql.*;
public class DatabaseHandler {
private Statement stmt;
private Connection con;
String username = "root";
String password = "thunder";
String dbname = "bidderboy";
public DatabaseHandler()
{
this.createConnection();
}
private void createConnection()
{
//create the connection for first time
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
stmt = con.createStatement();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public int executeUpdate(String sql)
{
int result = 0;
//before update checks if connection is open
try {
if(con.isClosed()) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
stmt = con.createStatement();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
//try to executeUpdate the sql command
try{
result = stmt.executeUpdate(sql);
}
catch(Exception ex){
System.out.println("Couldn't executeUpdate sql command");
}
return result;
}
public ResultSet executeQuery(String sql)
{
ResultSet rs = null;
//before Query checks if connection is open
try {
if(con.isClosed()) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbname , username , password);
stmt = con.createStatement();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
//try to executeQuery the sql command
try{
rs = stmt.executeQuery(sql);
}
catch(Exception ex){
System.out.println("Couldn't executeQuery sql command");
}
return rs;
}
public void closeConnection()
{
//if connection is open try to close the connection
try {
if(!con.isClosed()) {
con.close();
}
} catch (SQLException ex) {
System.out.println("Failed to close database connection");
}
}
}
The code of my servlet is:
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
public class UserLogin extends HttpServlet{
public UserLogin()
{
}
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DatabaseHandler dbh = new DatabaseHandler();
String username="mamun";
String password="1234";
String dbusername="";
String dbpassword="";
String sql = "select * from users where username='"+username+"' and password='"+password+"'";
ResultSet rs = dbh.executeQuery(sql);
try {
while(rs.next())
{
dbusername = rs.getNString(1);
dbpassword = rs.getNString(2);
}
} catch (SQLException e) {}
System.out.println(dbusername+" "+dbpassword);
}
}
And the Code of normal java class from which I'm getting my data is:
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseConnectionTest {
public static void main(String[] args) {
String sql = "Select * from users";
DatabaseHandler dbh = new DatabaseHandler();
ResultSet rs = dbh.executeQuery(sql);
try {
while(rs.next())
{
String n = rs.getNString(1);
String c = rs.getNString(2);
System.out.println("Name: "+n+" Contact: "+c);
}
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
}
Anybody please explain why I'm getting this class not found exception and What can be the solution. Thanks in advance.
Adding mysql-connector-java-5.1.11-bin.jar file to WEB-INF/lib folder fixed my problem.

Mysql database Exception

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
i am a beginner in java i am trying to use mysql database i have downloaded mysql-connector-java-5.1.23-bin.jar file from mysql.com and i have added this jar file to in my build path of my project but there is an error in the following code
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
package com.example.demo;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try
{
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}
}
Wrong classes
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
should be
import java.sql.Connection;
import java.sql.Statement;
In fact, java decouples everything from a specific database engine. One never should need an import of MySQL (or ProgressSQL or ...) classes.
To have those classes available at run-time, the first thing after the try, before getting the connection would be:
Class.forName("com.mysql.jdbc.Driver");
This technique would allow reading all strings from a configuration file, and writing database independent code.
Missing: conn = ...
conn = DriverManager.getConnection(CONN_STR, userName, userpwd);
package com.example.demo;
import java.sql.*;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}

MySQLConnection - Error on authenticateUser of "Multiple markers at this line"

I am trying to create my first MySQLConnection in Eclipse and am getting an error on authenticateUser of "Multiple markers at this line
- The return type is incompatible with
DBConnection.authenticateUser(String, String)"
I understand this means "that there is more than one error ... but I can't solve the issue...".
I am using http://altair.cs.oswego.edu/~tenberge/tenbergen.org/misc/DB-Access-in-GWT-The-Missing-Tutorial.pdf as my guide.
This is my code:
AwardTracker.gwt.xml
<module>
<inherits name="com.google.gwt.user.User"/>
<inherits name="com.google.gwt.user.theme.standard.Standard"/>
<entry-point class="org.AwardTracker.client.AwardTracker"/>
<!-- servelet context - path is arbitrary, but must match up with the rpc init inside java class -->
<!-- Tomcat will listen for this from the server and waits for rpc request in this context -->
<servelet class="org.AwardTracker.server.MySQLConnection"
path="/MySQLConnection" />
<inherits name="com.google.gwt.user.theme.standard.Standard"/>
<inherits name="com.google.gwt.user.theme.chrome.Chrome"/>
<inherits name="com.google.gwt.user.theme.dark.Dark"/>
User.java
package org.AwardTracker.client;
import com.google.gwt.user.client.rpc.IsSerializable;
public class User implements IsSerializable {
#SuppressWarnings("unused")
private String username;
#SuppressWarnings("unused")
private String password;
#SuppressWarnings("unused")
private User() {
//just here because GWT wants it.
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
}
MySQLConnection.java
package org.AwardTracker.server;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.AwardTracker.client.DBConnection;
import org.AwardTracker.client.User;
public class MySQLConnection extends RemoteServiceServlet implements DBConnection {
private Connection conn = null;
private String status;
private String url = "jbdc:mysql://localhost/awardtracker";
private String user = "DBuser";
private String pass = "DBpass";
public MySQLConnection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
//NEVER catch exceptions like this
}
}
public int authenticateUser(String user, String pass) {
User user;
try {
PreparedStatement ps = conn.prepareStatement(
"select readonly * from users where username = \"" + user + "\" AND " + "password = \"" + pass + "\"");
ResultSet result = ps.executeQuery();
while (result.next()) {
user = new User(result.getString(1), result.getString(2));
}
result.close();
ps.close();
} catch (SQLException sqle) {
//do stuff on fail
}
return user;
}
}
Any help would be greatly appreciated.
Regards,
Glyn
Hi BenvynQ,
Thanks for your help. Just goes to show that these tutorials are not perfect. I made this change and now I get an error within authenticateUser:
while (result.next()) {
user = new User(result.getString(1), result.getString(2));
}
Of "The constructor User(String, String) is undefined".
Thanks,
Glyn
Hi Bevnq,
Thanks awfully for your help. I think there were a few "}" missing so I have modified as following.
Also, you say "User user = null; // necessary unless you do something in the exception handler
". My impression of this is that we are trying to find out if the user is in the table and return an exception if they are not (i.e., verify the username and password). Therefore, the return needs to be a confirmation and therefore we are doing something with the exveption handler. I am obviously missing something; so how do we know the user has logged in successfully?
Also, Eclipse does not seem to have an issue with mixed case for the package as I am doing this in stages and all has worked up to adding this.
Regards,
Glyn
package org.AwardTracker.server;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.AwardTracker.client.DBConnection;
import org.AwardTracker.client.User;
public class MySQLConnection extends RemoteServiceServlet implements DBConnection {
private Connection conn = null;
private String status;
private String url = "jbdc:mysql://localhost/awardtracker";
private String user = "DBuser";
private String pass = "DBpass";
public MySQLConnection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, user, pass);
} catch (Exception e) {
//NEVER catch exceptions like this
}
}
public User authenticateUser(String userName, String pass) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(
"select readonly * from users where username = \"" + userName + "\" AND " + "password = \"" + pass + "\"");
result = ps.executeQuery();
while (result.next()) {
user = new User(result.getString(1), result.getString(2));
}
}
catch (SQLException sqle) {
//do stuff on fail
}
finally {
if (result != null) {
try {
result.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
return user;
}
}
You have defined the method
public int authenticateUser(String user, String pass) {
yet the object you are returning is
User user;
reading the tutorial looks like you should have declared the method
public User authenticateUser(String userName, String pass) {
User user = null; // necessary unless you do something in the exception handler
ResultSet result = null;
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(
"select readonly * from users where username = \"" + userName + "\" AND " + "password = \"" + pass + "\"");
result = ps.executeQuery();
while (result.next()) {
user = new User(result.getString(1), result.getString(2));
}
} catch (SQLException sqle) {
//do stuff on fail
}finally{
if (result != null) {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return user;

Categories