Retrieve values from database to jradiobutton - java

I'm trying to implement a payroll system and I got some issues with the updating employees. I have stored the gender of the employees as a varchar in my DB. When I type in the employee id and click search button I want to get that info out of the database and display it in a male/female radio buttons according to the data. There are no errors in the code. but the problem is when I try to do that only male button appear selected which is by the way the default. Female radio button doesn't get selected even when the the data on the DB says Female. Can anybody please help me with this issue? below is my code.
package AppPackage;
import static AppPackage.AddEmployeeGUI.convertUtilDateToSqlDate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class UpdateEmployeeGUI extends javax.swing.JFrame {
Connection conn=null;
PreparedStatement pst=null;
ResultSet rs=null;
public UpdateEmployeeGUI() {
initComponents();
conn=MySQLConnect.ConnectDb();
}
private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "SELECT * FROM EmployeeInfo WHERE EmployeeID =?";
pst=conn.prepareStatement(sql);
pst.setString(1,EmployeeIDSearchField.getText());
rs = pst.executeQuery();
if(rs.next()) {
String ID = rs.getString("EmployeeID");
EmployeeIDField.setText(ID);
String FN = rs.getString("FirstName");
FirstNameField.setText(FN);
String LN = rs.getString("LastName");
LastNameF.setText(LN);
String GN = rs.getString("Gender");
if (GN =="Female"){
MaleRadio.setSelected(false);
FemaleRadio.setSelected(true);
}
else{
FemaleRadio.setSelected(false);
MaleRadio.setSelected(true);
}
String CN = rs.getString("ContactNo");
ContactNoField.setText(CN);
String EM = rs.getString("Email");
EmailField.setText(EM);
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
Date dateValue = null;
try {
dateValue = date.parse(rs.getString("DateOfJoin"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
jDateChooser.setDate(dateValue);
String Des = rs.getString("Designation");
DesignationComboBox.addItem(Des); //getItemAt(int index);
String BS = rs.getString("BasicSalary");
BasicSalaryField.setText(BS);
}
} catch (SQLException e ) {
JOptionPane.showMessageDialog(null, e);
}
}
private void UpdateEmployeeButtonActionPerformed(java.awt.event.ActionEvent evt) {
// UPDATE EmployeeInfo SET FirstName='?', LastName='?', LastName='?', Gender='?', ContactNo='?',Email='?', DateOfJoin='?', Designation='?' WHERE EmployeeID='?';
try{
String sql1 = "UPDATE EmployeeInfo SET FirstName=?, LastName=?, Gender=?, ContactNo=?, Email=?, DateOfJoin=?, Designation=?, BasicSalary=? WHERE EmployeeID=?";
pst=conn.prepareStatement(sql1);
pst.setString(1,FirstNameField.getText());
pst.setString(2,LastNameF.getText());
pst.setString(3,GenderC);
pst.setString(4,ContactNoField.getText());
pst.setString(5,EmailField.getText());
pst.setDate(6,convertUtilDateToSqlDate(jDateChooser.getDate()));
pst.setString(7,DesignationComboBox.getSelectedItem().toString());
pst.setString(8,BasicSalaryField.getText());
pst.setString(9,EmployeeIDField.getText());
pst.execute();
String sql2 = "UPDATE employeebasicsalary SET BasicSalary=? WHERE EmployeeID=?";
pst=conn.prepareStatement(sql2);
pst.setString(1,BasicSalaryField.getText());
pst.setString(2,EmployeeIDField.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Successfully updated!");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
private void FemaleRadioActionPerformed(java.awt.event.ActionEvent evt) {
GenderC = "Female";
}
private void MaleRadioActionPerformed(java.awt.event.ActionEvent evt) {
GenderC = "Male";
}
private void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {
EmployeeIDField.setText(null);
FirstNameField.setText(null);
LastNameF.setText(null);
MaleRadio.setSelected(true);
FemaleRadio.setSelected(false);
ContactNoField.setText(null);
EmailField.setText(null);
jDateChooser.setCalendar(null);
BasicSalaryField.setText(null);
DesignationComboBox.setSelectedIndex(0);
}

replace the lines
if (GN =="Female"){
MaleRadio.setSelected(false);
FemaleRadio.setSelected(true);
}
else{
FemaleRadio.setSelected(false);
MaleRadio.setSelected(true);
}
with
if (GN.equals("Female")){
MaleRadio.setSelected(false);
FemaleRadio.setSelected(true);
} else {
FemaleRadio.setSelected(false);
MaleRadio.setSelected(true);
}
as == is used to compare the hash and values & .equals is used to check the values only..

Related

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

"data exception: division by zero" when inserting row

I am trying to insert data entered from a JFrame and series of textfields into my database table. I have been able to do so with smaller amounts of data, but Im having a lot of trouble with this.
<pre><code>
package Vegan;
import java.sql.Connection;
import java.sql.DriverManager;
public class connectionString {
static Connection connection = null;
public static Connection getConnection()
{
try
{
connection = DriverManager.getConnection("jdbc:ucanaccess://C:/Mo//MyDatabase1.accdb");
System.out.println("---connection succesful---");
}
catch (Exception ex)
{
System.out.println("Connection Unsuccesful");
}
return connection;
}
</pre></code>
<pre><code>
package Vegan;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DB {
private static ResultSet rs = null;
private static PreparedStatement ps = null;
private static Connection connection = null;
public DB() {
connection = connectionString.getConnection();
}
public void AddSupplier(String pw, String un, String sn, String cn, String ws, String pa, String city, String pv, String pc) throws SQLException
{
ps = connection.prepareStatement("INSERT INTO AccountTbl(StorePassword, Username, StoreName, ContactNo, Website, PhysAddress, City, Province, PostalCode) VALUES (?,?,?,?,?,?,?,?,?)");
ps.setString(1, pw);
ps.setString(2, un);
ps.setString(3, sn);
ps.setString(4, cn);
ps.setString(5, ws);
ps.setString(6, pa);
ps.setString(7, city);
ps.setString(8, pv);
ps.setString(9, pc);
ps.executeUpdate();
}
}
<pre><code>
package Vegan;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class SupplierReg extends javax.swing.JFrame {
private Object JOptionpane;
public SupplierReg() {
initComponents();
}
private void btnEnterActionPerformed(java.awt.event.ActionEvent evt) {
if ((txtAreaCode.getText().equals("")) || (txtCity.getText().equals("")) || txtContactNo.getText().equals("")
|| txtPassword.getText().equals("") || txtProvince.getText().equals("") || txtStoreName.getText().equals("") || txtStreetAddress.getText().equals("") || txtUsername.getText().equals("") || txtWebsite.getText().equals("")) {
JOptionPane.showMessageDialog(rootPane, "Please fill in all the information boxes");
} else {
try {
DB regDB = new DB();
regDB.AddSupplier(txtUsername.getText(), txtPassword.getText(), txtStreetAddress.getText(), txtStoreName.getText(), txtCity.getText(), txtContactNo.getText(), txtProvince.getText(), txtWebsite.getText(), txtAreaCode.getText());
} catch (SQLException ex) {
System.out.println(ex.getLocalizedMessage().toString());
}
setVisible(false);
new SupplierAbilityMenu().setVisible(true);
}
}
</pre></code>
When I insert my values I get an error message saying:
<pre><code>
run:
---connection succesful---
UCAExc:::3.0.6 data exception: division by zero
BUILD SUCCESSFUL (total time: 1 second)
</pre></code>
Im not too sure why it would say an error is being caused "division by zero", but I do not have any fields in the database that are of numerical fields.
EDIT: http://www53.zippyshare.com/v/DMLjdpDw/file.html Link to Access database
Your [AccountTbl] table contains three additional fields:
[TotalRating] - Long Integer, Default 0
[noRating] - Long Integer, Default 0
[overallRating] - Calculated: [TotalRating]/[noRating]
Since you are not supplying a value for [noRating] it is defaulting to zero, and therefore the [overallRating] calculation is trying to divide by zero.
You should change the default value of the [noRating] column to Null, so the [overallRating] calculation will return Null if no [noRating] is entered.

JDBC - Double Value Not Showing Up in MySQL DB

I have a program that is grabbing prices from web pages, and then finds the difference of that price from the last grabbed price, and then it sends that value to my MySQL Database.
Things to note before looking at the code:
The actual price, which is a double, does get sent and is entered into my Database correctly, although my priceChange variable is not. I have tried changing it to a BigDecimal and that made not changes.
PriceGrabber.java (sloppy right now, I know. I'm going to slim the code down eventually. once I get my core functions working.)
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.TimerTask;
import java.util.Date;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.*;
import java.lang.*;
import java.net.URL;
import java.io.*;
public class PriceGrabber extends TimerTask{
#Override
public void run() {
try {
if(Coinbase.getLastPrice() == Variables.getCoinbase()){
System.out.println();
}else {
System.out.println("Price Change Detected in Coinbase!");
System.out.println("Price Change: " + (Variables.getCoinbase() - Coinbase.getLastPrice()));
Coinbase.setLastPrice(Variables.getCoinbase());
Variables.addPrice(Variables.getCoinbase(), "Coinbase", (Variables.getCoinbase() - Coinbase.getLastPrice()));
}
if(BTCE.getLastPrice() == Variables.getBTCE()){
System.out.println();
}else {
System.out.println("Price Change Detected in BTC-E!");
System.out.println("Price Change: " + (Variables.getBTCE() - BTCE.getLastPrice()));
BTCE.setLastPrice(Variables.getBTCE());
Variables.addPrice(Variables.getBTCE(), "BTC-e", (Variables.getBTCE() - BTCE.getLastPrice()));
}
if(BitStamp.getLastPrice() == Variables.getBitStamp()){
System.out.println();
}else {
System.out.println("Price Change Detected in BitStamp Market!");
System.out.println("Price Change: " + (Variables.getBitStamp() - BitStamp.getLastPrice()));
BitStamp.setLastPrice(Variables.getBitStamp());
Variables.addPrice(Variables.getBitStamp(), "Bitstamp", (Variables.getBitStamp() - BitStamp.getLastPrice()));
}
if(Bitfinext.getLastPrice() == Variables.getBitfinext()){
System.out.println();
}else {
System.out.println("Price Change Detected in Bitfinext!");
System.out.println("Price Change: " + (Variables.getBitfinext() - Bitfinext.getLastPrice()));
Bitfinext.setLastPrice(Variables.getBitfinext());
Variables.addPrice(Variables.getBitfinext(), "Bitfinext", (Variables.getBitfinext() - Bitfinext.getLastPrice()));
}
//Variables.printPrices();
} catch (IOException e) {
}
}
}
Variables.java
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.TimerTask;
import java.util.Date;
import org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.*;
import java.lang.*;
import java.net.URL;
import java.io.*;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Enumeration;
public class Variables {
public static final String DB_URL = "jdbc:mysql://URL TO DB";
// Database credentials
public static final String USER = "username";
public static final String PASS = "password";
//Web Elements
public static URL url = null;
public static Document page = null;
public static Element priceElement = null;
public static Document doc = null;
public static String price;
public static String priceString;
public static String timeStamp;
//Different Market URL's
public static String coinbaseURL = "https://bitcoinwisdom.com/markets/coinbase/btcusd";
public static String btceURL = "https://bitcoinwisdom.com/markets/btce/btcusd";
public static String bitstampURL = "https://bitcoinwisdom.com/markets/bitstamp/btcusd";
public static String bitfinextURL = "https://bitcoinwisdom.com/markets/bitfinex/btcusd";
//Sets the URL
public static void setURL(String siteURL) throws MalformedURLException, IOException{
url = new URL(siteURL);
}
public static Double getCoinbase() throws IOException{
try{
setURL(coinbaseURL);
page = Jsoup.parse(url, 5000);
if(page.select("div.green").first() == null){
priceElement = page.select("div.red").first();
}else{
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
}catch(IOException e) {
System.out.println("something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public static Double getBTCE() throws IOException{
try{
setURL(btceURL);
page = Jsoup.parse(url, 5000);
if(page.select("div.green").first() == null){
priceElement = page.select("div.red").first();
}else{
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
}catch(IOException e){
System.out.println("oops! Something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public static Double getBitStamp() throws IOException {
try {
setURL(bitstampURL);
page = Jsoup.parse(url, 5000);
if (page.select("div.green").first() == null) {
priceElement = page.select("div.red").first();
} else {
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
} catch (IOException e) {
System.out.println("oops! Something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public static Double getBitfinext() throws IOException {
try {
setURL(bitfinextURL);
page = Jsoup.parse(url, 5000);
if (page.select("div.green").first() == null) {
priceElement = page.select("div.red").first();
} else {
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
} catch (IOException e) {
System.out.println("oops! Something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
//***********************************************************************************\\
//TODO:******************************************************************************\\
//TODO: SEARCH FOR QUEUE SYSTEM TO AVOID HAVING TO RECONNECT FOR EACH ADDITION \\
//TODO:******************************************************************************\\
//***********************************************************************************\\
public static void addPrice(Double price, String market, Double priceChange){
java.sql.Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
java.sql.Timestamp sqlDate = new java.sql.Timestamp(new java.util.Date().getTime());
String query = " insert into prices (market, price, pricechange, time_of_change)"
+ " values (?, ?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, market);
preparedStmt.setDouble (2, price);
preparedStmt.setDouble(3, priceChange);
preparedStmt.setTimestamp(4, sqlDate);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}//end main
}
I'm going to show you the source of Coinbase.java, it is the exact same as the other classes (BTCE.java, Bitfinext.java, etc.) Just to save space
Coinbase.java (Same as other market classes)
/**
* Created by Sullivan4653 on 12/8/2014.
*/
public class Coinbase {
public static double lastPrice = 0.0;
public static void setLastPrice(double price){
lastPrice = price;
}
public static double getLastPrice(){
return lastPrice;
}
}
**Finally my MySQL Information: **
My MySQL Database/Table and columns all work except my priceChange one. The value-type is set to Double. Default value = null. That is the SAME as my price column, which seems to be working because I'm getting values of the prices. (AKA not 0 every time like my PriceChange column)
My question is, why is this double now showing in my MySQL Database?
I apologize for the length of the post but I want to make sure I don't leave out any details that may help someone understand the problem. I've been struggling with it for a few days now and can't find the error!
Thanks!
Stop using static classes, go deeper into Java if you already want to make stuff like this :)
Also, if you want to provide code to others, please use some nice naming conventions, instead of making everything look like default variables (IE coinbaseURL, which should be something like COINBASE_URL, based on your modifiers).
In your code you're declaring the old value with a new value, so you're overriding it (you cannot use it anymore, because it changed to the new one).
Here's what I mean:
Coinbase.setLastPrice(Variables.getCoinbase());
Variables.addPrice(Variables.getCoinbase(), "Coinbase", (Variables.getCoinbase() - Coinbase.getLastPrice()));
I've simplified your code and improved it, this should work.
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* #author JKetelaar
*/
public class PriceGrabber implements Runnable {
private Coinbase coinbase;
private Variables variables;
public PriceGrabber(){
this.coinbase = new Coinbase(0);
this.variables = new Variables();
this.variables.connect();
}
public static void main(String[] args){
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new PriceGrabber(), 0, 10, TimeUnit.SECONDS);
}
#Override
public void run() {
try {
if (coinbase.getPrice() == variables.getCoinbase()) {
System.out.println("No changes found for Coinbase...");
} else {
System.out.println("Price Change detected in Coinbase!");
Double cbase = variables.getCoinbase();
Double cprice = coinbase.getPrice();
System.out.println("Old price: " + cprice + "\nNew price: " + cbase + "\nPrice Change: " + (cbase - cprice));
coinbase.setPrice(cbase);
variables.addPrice(cbase, "Coinbase", (cprice - cprice));
}
} catch (IOException ignored) {
}
}
}
-
public class Coinbase {
private double price = 0.0;
public Coinbase(double price) {
this.price = price;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
}
-
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
public class Variables {
public static final String DB_URL = "jdbc:mysql://160.153.49.168:3306/btcprogram";
// Database credentials
public static final String USER = "sully";
public static final String PASS = "asweq123e";
//Web Elements
public static URL url = null;
public static Document page = null;
public static Element priceElement = null;
public static Document doc = null;
public static String price;
public static String priceString;
public static String coinbaseURL = "https://bitcoinwisdom.com/markets/coinbase/btcusd";
private Connection connection;
//Sets the URL
public void setURL(String siteURL) throws IOException {
url = new URL(siteURL);
}
public Double getCoinbase() throws IOException {
try {
setURL(coinbaseURL);
page = Jsoup.parse(url, 5000);
if (page.select("div.green").first() == null) {
priceElement = page.select("div.red").first();
} else {
priceElement = page.select("div.green").first();
}
priceString = priceElement.toString();
doc = Jsoup.parse(priceString);
price = doc.body().text();
} catch (IOException e) {
System.out.println("something went wrong");
System.out.println(e.getMessage());
}
return Double.parseDouble(price);
}
public void addPrice(Double price, String market, Double priceChange) {
/**
* In your table set the time of change to a default value, so the table will do the time itself.
* Makes it easier for you and doesn't get complicated if you want to get others to insert prices.
*/
this.query("INSERT INTO prices (market, price, pricechange) VALUES (?, ?, ?)", new Object[]{
price, market, priceChange
});
}
public ResultSet query(String q, Object[] args) {
if (connection == null) {
System.out.println("No connection to the database.");
return null;
}
try {
PreparedStatement preparedStatement = connection.prepareStatement(q);
for (int i = 1; i <= args.length; i++) {
if (args[i] instanceof Double){
preparedStatement.setDouble(i, Double.parseDouble(String.valueOf(args[i])));
}else{
preparedStatement.setString(i, String.valueOf(args[i - 1]));
}
}
if (q.toLowerCase().startsWith("select")) {
return preparedStatement.executeQuery();
} else {
preparedStatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public void connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
.getConnection("jdbc:mysql://160.153.49.168:3306/btcprogram?"
+ "user=sully&password=asweq123e");
if (!connection.isClosed()) {
System.out.println("Successfully connected to the database...\nReady for SQL queries!");
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}

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?

Jtable how to display data from mysql in different Columns

I am trying to display data from the database in java using Jtable, yes I have achieved that but now the conflict is the surname and name they are displayed in one Column yet I would like them to be displayed in different columns . below is my code please help ..
import java.awt.Dimension;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.*;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ju {
private static Object request;
static JTable mysTable;
//constructor method
public static void main (String args []){
String [] columnNames = {"Name","Lastname","Id","Style"};
mysTable = new JTable(4,4);
mysTable.setBounds(20,10,300,300);
JFrame frame = new JFrame("King Musa Saloon Software");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(500,500);
frame.setResizable(false);
frame.setVisible(true);
frame.add(mysTable);
//frame.add(mysTable);
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loading success!");
String url = "jdbc:mysql://localhost:3306/saloon";
String name = "root";
String password = "";
try {
java.sql.Connection con = DriverManager.getConnection(url, name, password);
System.out.println("Connected.");
// pull data from the database
java.sql.Statement stmts = null;
String query = "select userid, username, name from saloonuser ";
stmts = con.createStatement();
ResultSet rs = stmts.executeQuery(query);
int li_row = 0;
while(rs.next()){
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
int userid = rs.getInt("userid");
String username = rs.getString("username");
String name1 = rs.getString("name");
System.out.println(name1);
li_row++;
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Take a look at your code here:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,0);
It's writing in the same column, you should change it to:
mysTable.setValueAt(rs.getString("username"),li_row,0);
mysTable.setValueAt(rs.getString("name"),li_row,1);
Try and see if it work :)

Categories