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());
Related
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();
I'm trying to update a table from a Java application where a certain column may be NULL. I have tried several different approaches but I always get the following error:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: 'null' for column 'scheidingsdatum' at row 1
I made sure that the table allowed NULL values for the scheidingsdatum field, and can insert NULL values when directly inserting in MySQL
This is the table structure in PHPMyAdmin:
The tables use innoDB
I have tried the following solutions:
1: Just use the NULL variable in a parameter
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = ? "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setString(4, scheidingsdatum);
stmnt.setString(5, nummer);
2: Hardcode NULL in the query (inside if/else block)
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = NULL "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setString(4, nummer);
3: Use setNull(4, java.sql.Types.DATE)
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = ? "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setNull(4, java.sql.Types.DATE);
stmnt.setString(5, nummer);
4: Use setNull(4, java.sql.Types.NULL)
stmnt = conn.prepareStatement("UPDATE gezinnen SET "
+ "ouder1 = ?,"
+ "ouder2 = ?,"
+ "huwelijksdatum = ?,"
+ "scheidingsdatum = ? "
+ "WHERE gezinsNummer = ?");
stmnt.setString(1, ouder1);
stmnt.setString(2, ouder2);
stmnt.setString(3, huwelijksdatum);
stmnt.setNull(4, java.sql.Types.NULL);
stmnt.setString(5, nummer);
the following is my database.properties file and connection creation:
database.properties
jdbc.drivers=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://IP:3306/TABLE_NAME
jdbc.username=USER
jdbc.password=PASSWORD
Connection creation
Class.forName(props.getProperty("jdbc.drivers")).newInstance();
this.conn = (Connection) DriverManager.getConnection(props.getProperty("jdbc.url"),props.getProperty("jdbc.username"),props.getProperty("jdbc.password"));
I just made a test and it worked for me with stmnt.setNull(4, java.sql.Types.Date);, are you sure that for stmnt.setString(3, huwelijksdatum); the value of huwelijksdatum is a valid mysql date string and not "null" ?
Well, this is the dumbest fix ever.
The code was originally made by someone else, and I only expanded on it a bit. They first created a string scheidingsDatum = "null";, which would then be overwritten by an actual date if there was one.
I assumed (I know, it's never smart to assume) that it would be null (Notice the lack of quotation marks?) when it didn't have a value.
So, in my check, the string wasn't null (since it was "null") and so the first part was executed. Which made it try to insert a string "null", which is obviously an incorrect date.
Simply modifying the string to be null instead of "null" upon instantiation fixed the issue.
You could try TIMESTAMP instead of DATE in your prepared statement.
stmnt.setNull(4, java.sql.Types.TIMESTAMP);
If scheidingsdatum is a nullable field, then simply remove it from your UPDATE statement when its value is null. In other words, when scheidingsdatum is null, change the statement to:
UPDATE gezinnen SET ouder1 = ?, ouder2 = ?, huwelijksdatum = ?
WHERE gezinsNummer = ?
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 MySQL database and want to write a row into it. The problem is that MySQL do not like my query, why? This is my code:
java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
for (Integer articlevalue : articlesendlist) {
for (Integer suppliervalue : suppliersendlist) {
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
}
}
A small description for my code. The articlesendlist contains IDs from selected values from a JTabel. The same applies to the suppliersendlist. I want to write the IDs into the table "Bestellung". The variable maxorder is the current ID for the table "Bestellung".
If you need it, the exception is:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '12:45:06.164, NULL)' at line 1
Please do not comment/answer with other links, I already searched for the problem and read several sites. They do not help me or are not suitable for my problem.
Thank you for help
Exception is obvious isn't it.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '12:45:06.164, NULL)' at line 1
You are not using quotes around date field.
However you should really avoid executing your SQL queries like this and use PreparedStatemens for this purpose.
PreparedStatemens has specific methods like setDate, setTime, setLong, setString etc and you don't need to worry about putting right quotes in your code.
Try changing this line:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES (" + maxorder + ", " + articlevalue + ", " + suppliervalue + ", " + date + ", NULL)");
to this:
connection.executeQuery("INSERT INTO Bestellungen(Bestellung_ID, Artikel_ID, Lieferant_ID, Datum, Preis) VALUES ('" + maxorder + "','" + articlevalue + "','" + suppliervalue + "','" + date + "','NULL')");
public List<Weather> getWeather(int cityId, int days) {
logger.info("days: " + days);
return getSimpleJdbcTemplate().query("SELECT weather.id, cities.name, weather.date, weather.degree " +
"FROM weather JOIN cities ON weather.city_id = cities.id " +
"WHERE weather.city_id = ? AND weather.date BETWEEN now()::date AND (now() + '? days')::date",
this.w_mapper, cityId, days);
}
error :
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [SELECT weather.id, cities.name, weather.date, weather.degree FROM weather JOIN cities ON weather.city_id = cities.id WHERE weather.city_id = ? AND weather.date BETWEEN now()::date AND (now() + '? days')::date]; The column index is out of range: 2, number of columns: 1.; nested exception is org.postgresql.util.PSQLException: The column index is out of range: 2, number of columns: 1.
it works with :
public List<Weather> getWeather(int cityId, int days) {
logger.info("days: " + days);
return getSimpleJdbcTemplate().query("SELECT weather.id, cities.name, weather.date, weather.degree " +
"FROM weather JOIN cities ON weather.city_id = cities.id " +
"WHERE weather.city_id = ? AND weather.date = now()::date",
this.w_mapper, cityId);
}
so the problem is when im using two ? marks in my query.
how can i make it work to with 2 ? marks???
The problem is probably in this part:
'? days'
The question mark is inside a literal string and so it is not recognized by the sql parser. You could try to rewrite it using the string concatenation operator, although I'm not 100% sure that is valid syntax in this case.
According to this page on the postgres wiki you should be able to simply omit the string 'days', since adding a date and an integer is interpreted as adding the specified number of days.
BETWEEN now()::date AND now()::date + ?
Rewrite the SQL part
AND weather.date BETWEEN now()::date AND (now() + '? days')::date
as
AND weather.date BETWEEN now()::date AND ?
and set it with a fullworthy java.sql.Date value instead of days.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, days);
Date endDate = new Date(calendar.getTimeInMillis());
// ...
(once again, it's java.sql.Date, not java.util.Date!)
The error is saying that you only have 1 param (ie a ?) in the first sql statement, but you are passing in two args. Spring doesn't know what to do with the second arg.