Writing data into MySQL table with JavaFX - java

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() + "')";

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;

why do I get the error massage java.lang.RuntimeException: java.sql.SQLException: No database selected in my java code(linking with mysql database) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
package persistentie;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import domein.Speler;
public class SpelerMapper {
private List<Speler> spelers = new ArrayList<>();
private List<Integer> scoreSpeler = new ArrayList<>();
private static final String UPDATE_SCORE = "insert into ID343589_g52.scoreSpeler(spelerNr,score) values(?,?)";
public SpelerMapper() {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement("SELECT * FROM ID343589_g52.speler");
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
String gebruikersnaam = rs.getString("gebruikersNaam");
String wachtwoord = rs.getString("wachtwoord");
spelers.add(new Speler(gebruikersnaam, wachtwoord));
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public boolean correcteGegevens(Speler nieuweSpeler) {
return spelers.contains(nieuweSpeler);
}
public List<Integer> geefscoreSpeler(String naam) {
scoreSpeler.clear();
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
int score = rs.getInt("score");
scoreSpeler.add(score);
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return scoreSpeler;
}
public void slaScoreOp(int score, String naam) {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
int id = 0;
while (rs.next()) {
id = rs.getInt("score");
}
PreparedStatement update = conn.prepareStatement(UPDATE_SCORE);
update.setInt(1, id);
update.setInt(2, score);
update.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
anything stupid I am doing here that is realy not how it working? I am really new to connecting a database with my java projects? the thing that I am trying to do in methode geefScoreSpeler() is getting the scores of an idividual player. and in methode slaScoreOp() I am trying to insert a new column in a table (also trying to get the id of the username via a table that innerjoins)
Hey there I made a user management system and this is my DAO(Databases connection class)
I have used prepared statement in this to see if it might help.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import com.ums.beans.ems.Employee;
public class EmployeeDao {
Connection connection;
Statement statement;
public EmployeeDao() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_1", "root", "apaar121");
}
public int saveEmployee(Employee employee) throws SQLException {
String query = "INSERT INTO user_1.employee ('name','dob','address','phone','email','education','designation','salary')VALUES (?,?,?,?,?,?,?,?);";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,employee.getName());
preparedStatement.setString(2,employee.getAddress());
preparedStatement.setString(3,employee.getDesignation());
preparedStatement.setString(4,employee.getDob());
preparedStatement.setString(5,employee.getEducation());
preparedStatement.setString(6,employee.getEmail());
preparedStatement.setString(7,employee.getPhone());
preparedStatement.setFloat(8,employee.getSalary());
return preparedStatement.executeUpdate();
}
}

Netbeans MySQL Connection - not to do with jbdc

I have a login app that needs to connect to a server to check the username and password. I am using netbeans and the jbdc is installed and working in the services tab(thanks stack overflow!). By the jbdc is work I mean that i can execute SQL script through it.
I have set this up with MS Server 16 and MySQL so I am convied it is the code:
Connection method:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String USERNAME = "root";
private static final String PASSWORD = "mess";
private static final String SQCONN = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection()throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(SQCONN, USERNAME, PASSWORD);
}catch (ClassNotFoundException e) {
}
return null;
}
}
loginmodel:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
Connection connection;
public LogInModel() {
try{
this.connection = dbConnection.getConnection();
}catch(SQLException e){
}
if(this.connection == null){
System.out.println("here");
// System.exit(1);
}
}
public boolean isDatabaseConnected(){
return this.connection != null;
}
public boolean isLogin(String username, String password) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
boolean bool1;
if(rs.next()){
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally {
{
pr.close();
rs.close();
}
}
}
}
I believe the issue is the return null; from the dbConnection file. The if(this.connection==Null) comes back true and the system is exiting.
Thank you in advance.
Your dbConnection class is a bad idea. Why hard wire those values when you can pass them in?
Your application will only have one Connection if you code it this way. A more practical solution will use a connection pool.
Learn Java coding standards. Your code doesn't follow them; it makes it harder to read and understand.
Here's a couple of recommendations:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "mess";
public static final String URL = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
I might write that LogInModel this way:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
private static final String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
private Connection connection;
public LogInModel(Connection connection) {
this.connection = connection;
}
public boolean isLogin(String username, String password) {
boolean isValidUser = false;
PreparedStatement pr = null;
ResultSet rs = null;
try {
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
while (rs.hasNext()) {
isValidUser = true;
}
} catch (SQLException ex) {
e.printStackTrace();
isValidUser = false;
} finally {
dbUtils.close(rs);
dbUtils.close(pr);
}
return isValidUser;
}
}
Here's my guess as to why your code fails: You don't have the MySQL JDBC driver JAR in your runtime CLASSPATH. There's an exception thrown when it can't find the driver class, but you didn't know it because you swallowed the exception.

Record not getting deleted from MySQL database's table while it's deleted from Java GUI?

Edited Question
When I click the delete button, The row in the table gets deleted in GUI but not from database in mysql server.
Here's the code:
// DatabaseStore. This part runs fine.
public class DatabaseStore {
private final String server = "jdbc:mysql://localhost/";
private final String database = "music_magic";
private final String user_name = "root";
private final String pass_word = "";
private final String driver = "com.mysql.jdbc.Driver";
public Connection doConnection() {
Connection c;
try {
//load the driver
Class.forName(driver);
c = DriverManager.getConnection(server + database, user_name, pass_word);
// JOptionPane.showMessageDialog(null, "Database connected");
} catch (Exception e) {
c = null;
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage());
}
return c;
}
//
// Imports
import Database_music.DatabaseStore; //main database page where i connect to database
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import magic_music.Items; //ignore this
//...
// Subject method
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(jTable1.getSelectedRow() >=0){
try{
DatabaseStore dtbs = new DatabaseStore();
Connection cn = dtbs.doConnection();
Statement stat = cn.createStatement();
String sql = "DELETE FROM products_info WHERE Product_id ='"+jTable1.getSelectedRow() +"'";
stat.executeUpdate(sql);
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.removeRow(jTable1.getSelectedRow());
}
catch (SQLException sqlException)
{
sqlException.printStackTrace();
JOptionPane.showMessageDialog(null, "sql err");
}
} else {
JOptionPane.showMessageDialog(null, "Please select an item to delete");
}
}
Please tell me what am I doing wrong?

NPE - java.lang.reflect.UndeclaredThrowableException

I'm working on web java application with OSGI. I get this error when I try to open JSF page: java.lang.reflect.UndeclaredThrowableException
This is the source code that I'm working on:
package org.DX_57.osgi.SH_27.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.DX_57.osgi.SH_27.api.SessionHandle;
public class SessionHandleImpl implements SessionHandle {
#Resource(name="jdbc/Oracle")
public DataSource ds;
public String sayHello(String name) {
return "Howdy " + name;
}
public String CheckUserDB(String userToCheck){
String storedPassword = null;
String error_Message = null;
String SQL_Statement = null;
String error_Database;
Connection conn;
try {
conn = ds.getConnection();
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
SQL_Statement = "SELECT Passwd from USERS WHERE Username = ?";
PreparedStatement passwordQuery = conn.prepareStatement(SQL_Statement);
passwordQuery.setString(1, userToCheck);
ResultSet result = passwordQuery.executeQuery();
if(result.next()){
storedPassword = result.getString("Passwd");
}
conn.commit();
committed = true;
} finally {
if (!committed) conn.rollback();
}
}
finally {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return storedPassword;
}
}
This is the error stack of the Glassfish server: http://pastebin.com/tvHmspjh
I can successfully compile the code but when I try to open JSF page I get error. Maybe I have mistaken the try-catch statements.
Best wishes

Categories