Error getting value from jdatechooser and adding it to database java - java

How can I show jcalender?
How to get the selected value from it and add it to database?
From google I found a file called jcalender-1.4. I've added it to the jframe but when I try to get selected value from it and add it to the database it shows error. Table is created but error shows while inserting values. The exception in insertion method is shown. I've tried to print the value the value of db9 by commenting the insertData method and it shows null. Below is the link of JCalender jar file that i've used.
https://www.dropbox.com/s/yxe86ylfm4u6be8/jcalendar-1.4.jar?dl=0
JButton btnNewButton = new JButton("New Reservation");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
db1=textField.getText();
db2=textField_1.getText();
db3=textField_2.getText();
db4=textField_3.getText();
db5=textField_4.getText();
db6=textField_5.getText();
db7=textField_6.getText();
db8=(String)comboBox.getSelectedItem();
db9=dateChooser.getDate();
db10=textField_7.getText();
db11=(String)comboBox_1.getSelectedItem();
db12=(String)comboBox_2.getSelectedItem();
db13=dateChooser_1.getDate();
db14=dateChooser_2.getDate();
try {
insertData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void createTable() throws Exception{
try{
Connection con=getConnection();
PreparedStatement create =con.prepareStatement("CREATE TABLE IF NOT EXISTS hotelDetails(_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,name varchar(65),"
+ "surname varchar(65),address varchar(65),cnic varchar(65),mobileNo varchar(65),email varchar(65),city varchar(65),gender varchar(65),dob Date,country varchar(65),roomType varchar(65),"
+ "roomNo varchar(65),checkin Date,checkout Date)");
create.executeUpdate();
System.out.println("Table Created");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Table Not Created.Try Again","Error", JOptionPane.ERROR_MESSAGE);
}
} public static void insertData() throws Exception{
try{
Connection con=getConnection();
PreparedStatement posted=con.prepareStatement("INSERT INTO hotelDetails(name,surname,address,cnic,mobileNo,email,city,gender,dob,country,roomType,roomNo,checkin,checkout)VALUES('"+db1+"','"+db2+"','"+db3+"','"+db4+"','"+db5+"','"+db6+"','"+db7+"','"+db8+"','"+db9+"','"+db10+"','"+db11+"','"+db12+"','"+db13+"','"+db14+"')");
posted.executeUpdate();
System.out.println("Values Inserted");
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Can't Insert Data","Error", JOptionPane.ERROR_MESSAGE);
}
}

Related

How do I pause my main thread so my JFrame can operate properly

I read a couple questions related to pausing main and both gave answers I didn't understand, and frankly I don't think are applicable.
I have a JFrame that makes use of a database I'm setting up in my driver class.
The JFrame will launch and the window opens; however when I try to make use of the database it fails; because back in main the program just keeps running and shuts down the connection, and closes it.
I tried just removing the connection.close() code just to see if my database methods work in the JFrame, and they do, so I just need to learn how to halt main while my JFrame is running.
public static void main(String[] args) {
File dbPropertiesFile = new File(DbConstants.DB_PROPERTIES_FILENAME);
if (!dbPropertiesFile.exists()) {
showUsage();
System.exit(-1);
}
try {
new Lab9(dbPropertiesFile).run(args);
} catch (Exception e) {
LOG.error(e.getMessage());
e.printStackTrace();
} finally {
shutdown();
}
}
private static void configureLogging() {
ConfigurationSource source;
try {
source = new ConfigurationSource(new FileInputStream(LOG4J_CONFIG_FILENAME));
Configurator.initialize(null, source);
} catch (IOException e) {
System.out.println(
String.format("Can't find the log4j logging configuration file %s.", LOG4J_CONFIG_FILENAME));
}
}
private static void shutdown() {
LOG.info("Shutting down");
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
LOG.error(e.getMessage());
e.printStackTrace();
}
}
}
private static void showUsage() {
System.err.println(
String.format("Program cannot start because %s cannot be found.", DbConstants.DB_PROPERTIES_FILENAME));
}
private Lab9(File file) throws IOException {
properties = new Properties();
properties.load(new FileInputStream(file));
database = new Database(properties);
}
/**
* Where the computer start making a lot of noise.
*
* #param args
* #throws Exception
*/
private void run(String[] args) throws Exception {
LOG.info("Running");
LOG.info("Loading database properties from: " + DbConstants.DB_PROPERTIES_FILENAME + ".");
LOG.info(properties.getProperty("db.driver"));
LOG.info("Driver loaded");
LOG.info("DB URL = " + properties.getProperty("db.url"));
LOG.info("DB USER = " + properties.getProperty("db.user"));
LOG.info("DB PASSWORD = " + properties.getProperty("db.password"));
connect();
Statement statement = connection.createStatement();
try {
// If the user enters the -drop switch
if (args[0].equalsIgnoreCase(DROP_COMMAND)) {
LOG.info("Table " + CustomerDao.TABLE_NAME + "is being DROPPED!");
customerDao.drop();
LOG.info("Table has been DROPPED!");
}
// Check to see if the table is already made; if its not then make it, and fill
// it.
if (Database.tableExists(CustomerDao.TABLE_NAME) == false) {
createTables(statement);
LOG.info("Created the table: " + CustomerDao.TABLE_NAME + ".");
LOG.info("Inserting Customer objects into table: " + CustomerDao.TABLE_NAME + ".");
insertCustomers();
LOG.info("Inserted customer info into table from file: [" + CUSTOMER_DATA + "].");
}
createUI();
// I NEED MAIN
// TO STOP
// AROUND HERE!
}catch(SQLException e){
e.printStackTrace();
LOG.error(e.getMessage());
}finally{
connection.close();
}
}
public static void createUI() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseControlFrame frame = new DatabaseControlFrame(customerDao);
frame.setVisible(true);
// OR MAYBE I NEED MAIN
// TO STOP
// AROUND HERE!
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void connect() throws SQLException {
connection = database.getConnection();
customerDao = new CustomerDao(database);
}
}
Any ideas? I tried using a while(frame.isVisilbe()){ wait(600) }; But the compiler had a spas when I tried to use wait().
You'll note I'm passing a customerDAO object to my JFrame constructor; but I'm beginning to wonder could I make a connection inside the JFrame so that when main's connection closes; my JFrame's doesn't? Is that a good idea? Is that even possible I'm not super SQL savvy I'm going to need to study up on it more.
You could use Thread.sleep() - I've found that useful with JFrame before, though I'm not 100% sure it would fit what you're looking for. If you want it to wait indefinitely, put it in a while loop:
while(//condition)
{
Thread.sleep(500); //pauses for .5 sec, then loops back to check condition
}
JFrame event handler runs on a different thread than main thread, so you need to shutdown on that thread.
Here is a example, Using JDBC with GUI API.
This example call connection.close() on received window-closing-event.
public class MyFrame extends JFrame {
public MyFrame() {
// ...
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(final WindowEvent e) {
shutdown();
System.exit(0);
}
});
}
// ...
}

Custom JtextField proprety [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I've created a custom JtextField but any proprety defined method don't working like getText or SetText when I call it in the main JFrame.
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class JTextFieldDecimal extends JTextField {
private static final long serialVersionUID = 1L;
public JTextFieldDecimal()
{
super();
addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
char c =e.getKeyChar();
if(!((c>='0') && (c<='9') ||
(c==KeyEvent.VK_BACK_SPACE) ||
(c==KeyEvent.VK_DELETE)))
{
getToolkit().beep();
e.consume();
}
}
});
}
}
when I click in validation button in jframe Produit the compiler give me an error and point to line 98 wich content my statement parameter of Custom JtextField named txtPrixHT.
btnValider.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Connection cn=null;
PreparedStatement pst =null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost/gesticom", "root","");
//String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT,PrRemise,PrPrixAchat,PrStockAlerte,PrStockReel) values (?,?,?,?,?,?,?)";
String sqlAdd ="insert into produit (PrCodeBarre,PrDesignation,PrPrixHT) values (?,?,?)";
pst=cn.prepareStatement(sqlAdd,Statement.RETURN_GENERATED_KEYS);
pst.setString(1, txtCodebarre.getText());
pst.setString(2, txtDesignation.getText());
pst.setString(3,txtPrixHT.getText());
pst.execute();
rs=pst.getGeneratedKeys();
if(rs.next())
{
txtIdprod.setText(rs.getString(1));
JOptionPane.showMessageDialog(null, "Nouveau Produit créé", "Fournisseur",JOptionPane.INFORMATION_MESSAGE);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try
{
cn.close();
pst.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
});
For an alternative to your formatted text field, I would propose you don't try to validate the input yourself. You can use a JFormattedTextField that allow you to do it for you when the focus is lost. Here is a quick sample
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter()
);
This will use the Locale of the JVM to format the number like expected (simpler for Decimal values). If you want only to take integers, provide an integer format
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter(
NumberFormat.getIntegerInstance()
)
);
You want to always have two decimal digit like 5.00, define it in the NumberFormat :
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMinimumFractionDigits(2);
JFormattedTextField decimalTxt = new JFormattedTextField(
new NumberFormatter(nf)
);
You can find more information about this on How to Use Formatted Text Fields

Add multiple rows in Oracle using Java

I have a text field and a button. When i enter data and click button it adds only one row.
public void widgetSelected(SelectionEvent e) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","nikshay");
Statement stmt=con.createStatement();
stmt.executeUpdate("create table sbase(person varchar(20),year number(2),gender varchar(1))");
PreparedStatement prepare=con.prepareStatement("insert into sbase (person,year,gender)values(?,?,?)");
prepare.setString(1,text.getText());
prepare.setString(2,text_1.getText());
prepare.setString(3,text_2.getText());
prepare.executeUpdate();
}
catch(Exception ex)
{
}
}
What should I do to add multiple rows.

java how to use a variable in method from another method

I have tried something like that : but the error appears:
SEVERE: null
null
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'MYUSER' cannot be null
while it shouldn't? Also I would like to ask if there are some bad practices in my program.
any tips?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
public class Main extends JFrame {
String text;
public Main() throws HeadlessException {
//opis
JLabel opis = new JLabel("Opis: ");
JTextField opisTextField = new JTextField();
opisTextField.setPreferredSize(new Dimension(100, 20));
add(opis);
add(opisTextField);
//jak klikniemy w przycisk program doda wartosci wpisane do bazy danych.
Button z = new Button("Dodaj do bazy danych");
add(z);
z.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e){}
#Override
public void mouseEntered(MouseEvent e){}
#Override
public void mouseExited(MouseEvent e){}
#Override
public void mouseReleased(MouseEvent e){}
#Override
public void mousePressed(MouseEvent e) {
Main m = new Main();
m.text = opisTextField.getText();
});
}
public void readDataBase() throws Exception {
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
// resultSet gets the result of the SQL query
// preparedStatements can use variables and are more efficient
preparedStatement = connect
.prepareStatement("insert into FEEDBACK.COMMENTS values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summary, COMMENTS from FEEDBACK.COMMENTS");
// parameters start with 1
preparedStatement.setString(1, text);
preparedStatement.executeUpdate();
// remove again the insert comment
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
// close();
}
}
public static void main(String[] args) throws Exception {
new Main().setVisible(true);
}
}
Sorry could not go through all the code but it looks like you declared String text; and you never provided it a value and you are passing this value to username preparedStatement.setString(1, text); which cannot be null as per error.

Getting NullpointerException in JDBC code

The following code is throwing a NullPointerException - I don't know where the problem is. I am using an Excel spreadsheet as a backend.
//actionlistener for btnfetch
btnfetch.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
try
{
String name="";
d1 = (java.util.Date)formatter.parse(textdate.getText());
java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
java.sql.Date sqld=null;
ResultSet rs=st.executeQuery("select * from [ARNUM$]");
String getname=null;
while(rs.next())
{
getname=rs.getString(1);
sqld=rs.getDate(2);
System.out.println(getname+" "+sqld+" "+sqlDate);
if(sqlDate.compareTo(sqld)==0)
{
name=name+" "+getname;
name=name.toUpperCase();
}
System.out.println(name);
}
if(name.length()==0)
{
JOptionPane.showMessageDialog(
pnlp4,
"No Name having "+textdate.getText(),
"Warning",
JOptionPane.WARNING_MESSAGE
);
}
else
{
textname.setText(name);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}//end actionPerformed
}); //end addActionListener
The field value of sqld might be null. Now unfortunately sqlDate.compareTo(null) will throw a NullPointerException. (Other compareTo's behave better.)

Categories