I can't find a way of putting all the selected items on 3 different combobox which I need to insert as query to Java DB(derby). Here's my code.
int response = JOptionPane.showConfirmDialog
(null, "Do you want to add the employee?","Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
if(response == JOptionPane.YES_OPTION){
try{
String url="jdbc:derby://localhost:1527/EMPLOYEEINFO [ADMIN1 on ADMIN1]";
String username="ADMIN1";
String password="ADMIN1";
Connection con = DriverManager.getConnection(url, username, password);
Statement stat = con.createStatement();
String Query =
"INSERT INTO EMPLOYEE (EMPLOYEE_ID,EMP_LASTNAME,EMP_FIRSTNAME,EMP_MIDDLENAME,ADDRESS,POSITION ) "
+"VALUES "
+ "(' "+AddEmployee_EmployeeID_TxtField.getText()+" ',"
+ " ' "+AddEmployee_LastName_TxtField.getText()+" ',"
+ " ' "+AddEmployee_FirstName_TxtField.getText()+" ',"
+ " ' "+AddEmployee_MiddleName_TxtField.getText()+" ',"
+ " ' "+AddEmployee_Address_TxtField.getText()+" '"
+ " ' "+AddEmployee_Position_TxtField.getText()+" ',"
+ " ' "+AddEmployee_Gender_ComboBox.getSelectedItem()+"')"
;
stat.execute(Query);
JOptionPane.showMessageDialog(null,"Insert Success!");
And below is the screenshot. I'm thinking of getselectedObject but i have 3 combo boxes so I really don't know how. Please help.
I need to get the selected items of Month, Day and Year of the Birthday then insert it to my table in Derby. Thanks in advance.
You should create a separate method to get the fields and combine the values into a formatted date. Something like this:
private String getDateFromFields() {
String month = monthComboBox.getSelectedItem();
String day = dayComboBox.getSelectedItem();
String year = yearComboBox.getSelectedItem();
// Format this the way your database expects.
String formattedDate = month + "/" + day + "/" + year;
}
You just call this method and you will get back the formatted date string that you can use in your query. Change the variable names of the combo box fields to match your names and format the string into what your database expects and you should be good to go!
You can do something like this:
String bDay=dayCombo.getSelectedItem()+"-"+monthCombo.getSelectedItem()+"-"+yearCombo.getSelectedItem();
But I will recommend you to use JDatechooser in this case.
JDateChooser bDayChooser =new JDateChooser();
bDayChooser.setDateFormatString("dd-MM-yyyy");//format visible date of the date chooser as you need
String bDay=((JTextField) bDayChooser.getDateEditor().getUiComponent()).
getText();
Related
I have 2 datebox to make a filter. Their value will determine the 'from' and 'to' in my query (I'm using Oracle now), here is the code.
#Listen("onClick=#btnSaveFilter")
public void saveFilter() throws Exception {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
c_main_filter.detach();
cc.refreshFilter(""
+"[Date of Birth] between '" + formatter.format(dbDateBirthFrom.getValue()).toString() + "' "
+ "and '" + formatter.format(dbDateBirthto.getValue()).toString() + "'");
}
when both datebox has value, the query work. but when they have no value the query is giving no data.
when datebox has value, it's giving data
"[Registration Date] between '2010-09-23' and '2010-09-23' "
when datebox has no value, it's giving no data
"[Registration Date] between '' and '' "
like another filter I expect if the value is '' then all data will appear, but not :D hahaha. the condition is more than this actually, the filter has a lot of parameter one of them is this condition, and some of them use date format so there will be more condition like this.
do you know how to elegantly fix this problem, I've been thinking to use 'if' to determine the datebox has value or no then I will append the text to query text if both of them has value, but then I found another problem how I can add 'and' in query to give another condition,
let say I have 5 conditions so then
"select * from xxxx where 1stcondition and 2ndcondition and
3rdcondition and 4thcondition and 5th condition"
so when the dateboxes of the 5thcondition has no value the query will be wrong like this
"select * from xxxx where 1stcondition and 2ndcondition and
3rdcondition and 4thcondition and"
if I want to use 'if' how can I play with the 'and'? but if you have alternative it will be great cause I don't have to deal with 'if' :D
You can use String.isEmpty() to determine whether you need to put an and:
String where = "";
if (from != null && to != null) {
where += <yourDateCondition>;
}
if (<needToAddSecondCondtion>) {
if (!where.isEmpty()) {
where += " and ";
}
where += <secondCondition>;
}
// continue with other conditions
String query = "select * from xxxx where " + where;
I don't know if you use plain JDBC or ORM framework like hibernate to querying to the database, but you can try something like this :
public void saveFileter(){
StringBuilder sb = new StringBuilder();
sb.append("select * from table ");
if(dbDateBirthFrom.getValue() != null{
sb.append(determineFilterWord(sb.toString()));
sb.append("your condition ");
}
if(dbDateBirthTo.getValue() != null{
sb.append(determineFilterWord(sb.toString()));
sb.append("your condition ")
}
session.createQuery(sb.toString()); //if you using hibernate
}
private string determineFilterWord(String query){
if(query.toLowerCase().indexOf("where") != -1){
return "and ";
}else{
return "where ";
}
}
This question already has answers here:
How does a PreparedStatement avoid or prevent SQL injection?
(10 answers)
Closed 7 years ago.
I am trying to make a to-do list using NetBeans-8.0.2 and JavaFX (FXMLApplication) that stores memory into MySQL database.
I know that, SQL query takes inverted comma -> ( ' ) and
double quotation -> ( " ) as the same to understand a string.
Now, what i am trying is, (today is my sister's birthday) i am trying to add a task in my list that says: It's Rahi's birthday!
but, due to sql query, it is failing.
it's because inside the code, input's inverted comma is making a complexity in the sql query as a whole.
#FXML
private void handleAddTaskAction(ActionEvent event) {
String date = addTaskDatePicker.getValue().toString();
System.out.println(date);
String hour = hourComboBox.getValue() + "";
String minute = minuteComboBox.getValue() + "";
String where = whereField.getText();
String header = headerField.getText();
String description = descriptionArea.getText();
if(hour.length()==0)
hour= "12 AM";
if(minute.length()==0)
minute= "00";
if(header.length()==0)
header= "(No header available)";
if(description.length()==0)
description= "(No description available)";
if(header.length()==0 && description.length()==0){
header= "(Empty task)";
description= "(Empty description)";
}
String query = "insert into task values('" + date + "','" + hour + " " + minute + " minutes', '"
+ header + "', '" + description + "', 'at " + where + "');";
if (date.length() >= 1) {
try {
statement.execute(query);
} catch (SQLException ex) {
//Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText("Error occured!");
alert.showAndWait();
}
} else {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setHeaderText("You must select a date.");
alert.showAndWait();
}
}
i want to store the message as it is typed. Any solutions ?
my database table description and The GUI are attached as picture.
Ask me if you need anything else.
Thank you.
Picture of: GUI and
Picture of: Table description
Just use a PreparedStatement to inject your values, it will escape them for you.
I am trying to do a SalesForce query from Java, and I want to insert the current date and time into the query. However, I also want to add a wildcard for title, and the percent for the wildcard is being interpreted as a format specifier and giving an error.
String soqlQuery = new String.format("SELECT Id, Title, CreatedDate "
+ "FROM FeedItem "
+ "WHERE title like '%ven%' and createdDate %s ", timeOfLastQuery);
I was able to just use string concatenation to get around the problem, but I would like to know if there is a way to do create a query string that contains a wildcard specifically using formatted strings.
You can escape them with another % like
String soqlQuery = new String.format("SELECT Id, Title, CreatedDate "
+ "FROM FeedItem "
+ "WHERE title like '%%ven%%' and createdDate %s ", timeOfLastQuery);
I want to insert a time which is taken from a textbox to the mysql database TIME column. I suppose I need to convert String to TIME like converting String to Date in mysql using "STR_TO_DATE" in the query. I looked for answers but I didn't get the answer I required.
Edit: SQL from comments:
"insert into schedules (
courseid,
batch,
subjectid,
teacherid,
stime,
etime,
date,
location,
building,
department,
hall,
status
) values ('" +
getCourse() + "','" +
getBatch() + "', '" +
getSubject() + "','" +
getTeacher() + "', '" +
getStime()+ "','" +
getEtime()+
"',STR_TO_DATE('" + getDate() + "','%d-%m-%Y'),'" +
getLocation() + "', '" +
getBuilding() + "', '" +
getDepartment()+ "', '" +
getHall() +
"','ACTIVE')"
As stated in comments Mysql accepts simple strings like '05:12:59' into TIME type columns but lets try to have another answer to it to. Check the format of date you get from textbox and edit Simple date format. You can try below.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parsedDate = dateFormat.parse(request.getParameter("textBoxName"));
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());//or you can assign this stuff to stime variable
I assume you are using preparedStatement as I think you will inserting many times. If so you can set the parameter like this.
preparedStatement.setTimestamp(1, timestamp);//1 is the index of parameter you can choose named parameters too
Also you can choose the to set stime and pass it in query using its relative getter.
I have a need to use Statement.executeUpdate() to insert data into Database.
So every parameter must be embeded into a SQL string.
In Database, the type of two columns are datetime: Date1 and Date2
At client side, if I use following statement:
String SQLString = "INSERT INTO Position (" +
......
"Date1, " +
......
"Date2) " +
"VALUES(" +
......
//"2012-05-29 16:28:58.555" + ", " + // runtime error, always say error at 16
//"2012-05-29" + ", " + // no runtime error, but lost time and result date is also not correct
//"10-06-02" + ", " + // no runtime error, but it adds 2 days beginning at 1900-01-01 00:00:00.000
......
null
")";
Can anyone tell me how to correctly embedded Datetime into SQL String?
You should use a PreparedStatement and pass the date field ad Date ...
String SQLString = "INSERT INTO Position (Date1) VALUES (?)";
PreparedStatement prest = con.prepareStatement(SQLString);
prest.setDate(1,new Date());
prest.executeUpdate()
First up, you have to use PreparedStatement. Then you could do something like:
statement.setDate(2, new Date());