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

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;

Related

How can I get data from DAO through the model and append them in the view [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
I am new to Java and I am trying to implement a login system and a user profile conform to MVC - DAO. I would like to enable the controller trough the method addUserDatatoView() to retrieve the user credentials from DAO, in order to add them as strings in a new JPanel (view). Anyway, I am not sure that my way to proceed is correct. First of all, I am getting all the time the NullPointerException, event though the DAO-level is getting correctly the data from the database:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "model.User.getUserName()" because "this.user" is null
at controller.LoginController.addUserDatatoView(LoginController.java:75)
at controller.LoginController.showHome(LoginController.java:65)
at controller.LoginController$LoginListener.actionPerformed(LoginController.java:44)
How can I actually retrieve the data from DAO passing through the Model (User class)? What would be the best way to deploy to data as strings from the controller to the view?
I am quite confused about the communication between the different classes and what is the correct procedure, in order not to contravene MVC-DAO.
I am not asking you to solve the problem, but to get an hint in order to get the right direction.
DAO-Implementation:
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import controller.HomeController;
import ds.OracleDsSingleton;
import model.Event;
import model.User;
import view.HomeView;
import view.LoginView;
import view.ProfileView;
public class DaoImpl implements DAO {
LoginView view;
ProfileView profView;
ResultSet rs;
public DaoImpl(LoginView view, ProfileView profView) {
this.view = view;
this.profView = profView;
}
#Override
public ArrayList<User> getUserLogIn (String userName, String userPass) throws SQLException {
OracleDsSingleton ora = OracleDsSingleton.getInstance();
boolean controlRecords = false;
try {
//ArrayList type User
ArrayList<User> user = new ArrayList<User>();
Connection con = ora.getConnection();
Statement stmt = con.createStatement();
String addQuery = "SELECT * FROM UserList";
ResultSet rs = stmt.executeQuery(addQuery);
while (rs.next()) {
userName = rs.getString("userName");
userPass = rs.getString("userPass");
if (userName.equals(view.getUserNameTextField().getText().toString())
&& (userPass.equals(view.getUserPassTextField().getText().toString()))) {
{
controlRecords = true;
User u = new User(userName, userPass);
user.add(u);
for(User us : user) {
System.out.println("Directly from DAOImp: " + us);
}
return user;
}
}
else {
continue;
}
}
if (!controlRecords) {
JOptionPane.showMessageDialog(null, "Not successfully logged in!");
};
if (con != null)
con.close();
if (stmt != null)
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
Class User:
public class User {
String userName;
String userPass;
public User(String userName, String userPass) {
this.userName = userName;
this.userPass = userPass;
}
public User() throws SQLException {
}
public String getUserName() {
return userName;
}
public String getUserPass() {
return userPass;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String toString() {
return userName + userPass;
}
}
Controller
package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JComponent;
import controller.LoginController.LoginBACKListener;
import dao.DAO;
import dao.DaoImpl;
import model.User;
import view.HomeView;
import view.LoginView;
import view.ProfileView;
import view.StartView;
public class LoginController{
private User user;
private LoginView view;
private ProfileView profView;
public LoginController(User user, LoginView view) {
this.user = user;
this.view = view;
addListener();
}
private void addListener() {
this.view.setLoginListener(new LoginListener());
}
class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = view.getUserNameTextField().getText();
String pass = view.getUserPassTextField().getText();
DAO myDAO = new DaoImpl(view, profView);
try {
//when method from DAOImpl get filled, proceed to Home
if(myDAO.getUserLogIn(name, pass) != null) {
showHome();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
public void showHome() {
HomeView home = new HomeView();
home.setVisible(true);
HomeController h = new HomeController(home);
try {
addUserDatatoView();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<User> addUserDatatoView() throws SQLException {
DAO myDAO = new DaoImpl(view, profView);
ArrayList<User> userCredentials = myDAO.getUserLogIn(user.getUserName(), user.getUserPass());
for(User us : userCredentials) {
System.out.println("Directly from Controller: " + us);
}
return userCredentials;
}
}
It is hard to tell from the partial code in the question, but from what I see, a User object can be constructed only after a successful login. so the constructor should change to:
public LoginController(LoginView view) {
this.view = view;
addListener();
}
And
class LoginListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = view.getUserNameTextField().getText();
String pass = view.getUserPassTextField().getText();
DAO myDAO = new DaoImpl(view, profView);
try {
user = myDAO.getUserLogIn(name, pass);//change getUserLogIn to return a single User, or null
//when method from DAOImpl get filled, proceed to Home
if(user != null) {
showHome();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}

Writing data into MySQL table with JavaFX

I have linked up a database to my Java application using the JDBC in Netbeans.
But whenever I try to write something from a TextField to a MySQL table, it doesn't work.
I have a pre-made class to make the database connection.
Here is my database class:
package testswitch;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Maarten
*/
public class Database {
public final static String DB_DRIVER_URL = "com.mysql.jdbc.Driver";
public final static String DB_DRIVER_PREFIX = "jdbc:mysql://";
private Connection connection = null;
public Database(String dataBaseName, String serverURL, String userName, String passWord) {
try {
// verify that a proper JDBC driver has been installed and linked
if (!selectDriver(DB_DRIVER_URL)) {
return;
}
if (serverURL == null || serverURL.isEmpty()) {
serverURL = "localhost:3306";
}
// establish a connection to a named Database on a specified server
connection = DriverManager.getConnection(DB_DRIVER_PREFIX + serverURL + "/" + dataBaseName, userName, passWord);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
private static boolean selectDriver(String driverName) {
// Selects proper loading of the named driver for Database connections.
// This is relevant if there are multiple drivers installed that match the JDBC type.
try {
Class.forName(driverName);
// Put all non-prefered drivers to the end, such that driver selection hits the first
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver d = drivers.nextElement();
if (!d.getClass().getName().equals(driverName)) {
// move the driver to the end of the list
DriverManager.deregisterDriver(d);
DriverManager.registerDriver(d);
}
}
} catch (ClassNotFoundException | SQLException ex) {
logException(ex);
return false;
}
return true;
}
public void executeNonQuery(String query) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(query);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
public ResultSet executeQuery(String query) {
Statement statement;
try {
statement = connection.createStatement();
ResultSet result = statement.executeQuery(query);
return result;
} catch (SQLException eSQL) {
logException(eSQL);
}
return null;
}
private static void logException(Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
}
And here's my JavaFX controller.
What I want is that when the "handle" button is pressed, that the data filled in the TextField gets inserted into the database.
package testswitch;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import testswitch.Database;
/**
*
* #author Maarten
*/
public class gebruikerToevoegenController {
//TextFields
#FXML
private TextField FXVoornaam, FXTussenvoegsel, FXAchternaam, FXGebruikersnaam;
#FXML
private TextField FXWachtwoord, FXEmail, FXTelefoonnummer;
//Boolean checkbox positie
#FXML
private CheckBox ManagerPosition;
#FXML
private Button gebruikerButton;
public final String DB_NAME = "testDatabase";
public final String DB_SERVER = "localhost:3306";
public final String DB_ACCOUNT = "root";
public final String DB_PASSWORD = "root";
Database database = new Database(DB_NAME, DB_SERVER, DB_ACCOUNT, DB_PASSWORD);
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES " + FXVoornaam.getText();
try {
database.executeQuery(query);
} catch (Exception e) {
}
}
}
Thanks in advance
The string in your SQL query doesn't seem to be properly quoted. It's best to use PreparedStatement for this scenario:
public class Database {
public PreparedStatement prepareStatement(String query) throws SQLException {
return connection.prepareStatement(query);
}
...
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES (?);";
PreparedStatement statement = database.prepareStatement(query);
try {
statement.setString(1, FXVoornaam.getText());
statement.executeUpdate();
} catch (Exception e) {
// log info somewhere at least until it's properly tested/
// you implement a better way of handling the error
e.printStackTrace(System.err);
}
}
You have to add like this in JavaFx :
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES ('{FXVoornaam.getText()}') ";
String query = "INSERT INTO testDatabase.Gebruikers(Voornaam)
VALUES('" + FXVoornaam.getText() + "')";

Calling method in Java

I want to connect with mysql db by using host, username, password from file aplikacja.properties. But I have problem bcs those method return null and I don't know why ?
getHost()
getUsername()
getPassword()
getDb()
package aplikacja.mysql;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class Mysql {
private String host;
private String username;
private String password;
private String db;
public void readConnectionParam() throws FileNotFoundException, IOException {
Properties mysqlAplikacjaProperties = new Properties();
FileInputStream mysqlPlik = new FileInputStream("aplikacja.properties");
mysqlAplikacjaProperties.load(mysqlPlik);
host = mysqlAplikacjaProperties.getProperty("jdbc.host");
username = mysqlAplikacjaProperties.getProperty("jdbc.username");
password = mysqlAplikacjaProperties.getProperty("jdbc.password");
db = mysqlAplikacjaProperties.getProperty("jdbc.db");
}
public String getHost() {
return host;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getDb() {
return db;
}
public static void main(String[] args) throws SQLException {
Mysql baza = new Mysql();
System.out.println(baza.getUsername());
Connection polaczenie = null;
String driver = "com.mysql.jdbc.Driver";
try {
Class.forName(driver).newInstance();
polaczenie = DriverManager.getConnection(
"jdbc:mysql://" + baza.getHost() + "/" + baza.getDb(),
baza.getUsername(), baza.getPassword());
} catch (Exception e) {
e.printStackTrace();
}
Statement statement = polaczenie.createStatement();
String command = "INSERT INTO users (id, name, surname) VALUES (2, 'Tom', 'Suszek')";
statement.executeUpdate(command);
}
}
Thanks for help.
I don't see any code that calls the readConnectionParam method, which is the only thing that can initialize the variables that are returned in your methods that are returning null. Call it.
You have to call readConnectionParam() Method since thesse fields are initialized here.
Try:
Mysql baza = new Mysql();
baza.readConnectionParam();
System.out.println(baza.getUsername());
Include the above code in a try catch since the method readConnectionParam() throws Exceptions
You should first initialize your vars calling the method
readConnectionParam
inside the main
use -
baza.readConnectionParam();
after
Mysql baza = new Mysql();
statement.

How to access and ArrayList inside another class inside multiple try's?

I have a homework to retrieve a myqsl query and save it to a ArrayList , and then to link it to another class and then serialize it and send it through http,
In a scheme it would be
class Server{static class a {try{try{ try{arraylist1} }}}}
class b {var1,var2,link_to(arraylist1)}
then serialize class b and send it
i managed to take the sql query and save the objects in the ArrayList (objects created from class "Personat") through
if (rs != null) {
List<Personat> perList = new ArrayList<Personat>();
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("var1"));
per.setName(rs.getString("var2"));
per.setAmount(rs.getInt("var3"));
perList.add(per);
}
}
Where rs=ResultSet object
but i cant access the ArrayList from class b so i can serialize it. I have tried to make it static (nothing ,it cant be linked).I have tried to make a getter (yet nothing eclipse wont let me as i automatically generate them).
So i don't know what i should do ! Can someone help me ? Or does anyone have any idea?
i have tried to search google for this but as you can see is a little too specific so no results until now ....
here is my Server.java
package server2;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
private static List<Personat> perList = new ArrayList<Personat>();
//need to access this in the SendRes class
public List<Personat> getPerList() {
return perList;
}
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null);
server.start();
}
static public class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
//
final String url = "jdbc:mysql://localhost/httpServer";
final String user = "root";
final String password = "";
try {
Send oin = (Send) ios.readObject();
int id = oin.getId();
String emri = oin.getName();
int amount = oin.getAmount();
int paid = oin.getPaid();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,
password);
try {
PreparedStatement s = con
.prepareStatement("INSERT INTO person(ID,Name,Amount,Paid) VALUES (?,?,?,?)");
s.setInt(1, id);
s.setString(2, emri);
s.setInt(3, amount);
s.setInt(4, paid);
s.executeUpdate();
ResultSet rs = s.executeQuery("SELECT * "
+ "from personat ORDER BY EmpId");
if (rs != null) {
while (rs.next()) {
Personat per = new Personat();
per.setID(rs.getInt("ID"));
per.setName(rs.getString("Name"));
per.setAmount(rs.getInt("Amount"));
perList.add(per);
}
}
//here i need to send an SendRes object with the ArrayList inside it
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
class SendResponse implements Serializable {
String gabim;
String gabimNr;
//link the arraylist from class server here
}
class Personat {
int ID;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAmount() {
return Amount;
}
public void setAmount(int amount) {
Amount = amount;
}
String Name;
int Amount;
}
Objects of type B can only access the public members of type A. To get access to your list you need to make it a public member of A. The typical way to do this is to use a private field and a public getter.
class A
{
private List<Personat> personList;
public List<Personat> getPersonList() { return personList; }
public void handle(HttpExchange t) throws IOException
{
// ...
personList = ...;
// ...
}
}
Note that by giving public access to your list you are also allowing clients to modify the contents of the list. You may prefer to give them a copy of the list if this is not desirable.
On a slightly unrelated note, if you three nested try blocks in a single method then that method is probably too complex and should be refactored into smaller methods.

Java - JDBC driver and MySQL database connection issues

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

Categories