I need to insert Date to my database, so I convert date received from user to SQL Date and then try to insert date to database. But in process SQL date object is evaluate to integer and thus insertion fails .
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String enrollNo = request.getParameter("enroll_no");
String name = request.getParameter("name");
String age = request.getParameter("age");
java.util.Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("dob"));
} catch (ParseException e) {
e.printStackTrace();
}
Date SqlDate = new Date(date.getTime());
process(enrollNo, name, age, SqlDate);
response.sendRedirect("listing.jsp");
}
void process(String enrollNo, String name, String age, Date date) {
DatabaseOperations db = new DatabaseOperations("java", "root", "", "jsp");
db.insert(enrollNo, name, age, date);
}
Insert method of DatabaseOperations class
public int insert(Object...objects) {
int rowsAffected = 0;
String query = "INSERT INTO " + tableName + " VALUES (";
for(int i=0; i<objects.length-1; i++)
query += "'" + objects[i] + "',";
query += objects[objects.length-1] + ")";
try {
rowsAffected = statement.executeUpdate(query);
} catch (SQLException e) {
printSQLExceptions(e);
}
return rowsAffected;
}
While inserting date 11/02/2000 following error shows up
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect date value: '1987' for column 'Dob' at row 1
Related
I catch the exception (I specially do mistake in SQL statement to get SQLException) when import records to database and I want in this catch update record in another table (in normal situation when we don't have an exception I also run this statement after importing records). But the problem is that record in another table not updated, however, in console I see that this updating successfull.
Firtsly, whem user import from FE records, in BE we get this POST-request in controller (It_tableController), after that call sevice (It_tableService) and service call DAO (It_tableDAO). And in DAO method I catch the SQLException (in It_tableDAO) and try to update record in another table (using import_sessionsDAO), but it doesn't works.
So why sql statement executes but not updates the record in catch block?
it_tableController.java:
#RequestMapping(value = "/*URL*/",
method = RequestMethod.POST)
#PreAuthorize("hasRole('USER')")
public ResponseEntity<List<EntityResponse>> addData(#PathVariable Integer originator_id,
#PathVariable Integer deployment_type_id,
#PathVariable Integer template_id,
#PathVariable String filename,
#RequestBody String[][] data,
#CurrentUser UserPrincipal currentUser) {
logger.info("Performing /*URL*/ POST request");
List<EntityResponse> response = it_tableService.addData(
deployment_type_id,
template_id,
originator_id,
filename,
currentUser.getId(),
currentUser.getUsername(),
data);
return new ResponseEntity<List<EntityResponse>>(response, HttpStatus.ACCEPTED);
}
It_tableService.java:
public List<EntityResponse> addData (
Integer deployment_type_id,
Integer template_id,
Integer originator_id,
String filename,
Long user_id,
String username,
String[][] data) {
if (!import_sessionsDAO.retrieveActiveImport_sessions(deployment_type_id).isEmpty())
{ return null; }
else {
Timestamp timestamp = import_sessionsDAO.insertImport_session(username, deployment_type_id, true, filename);
List<EntityResponse> responseItTable = new ArrayList<EntityResponse>();
responseItTable =
it_tableDAO.addData(deployment_type_id, template_id, originator_id, filename, user_id, username, data);
import_sessionsDAO.updateStatusOfImport_session(false, username, deployment_type_id, filename);
return responseItTable;
}
}
public Integer retrieveLastIdInTable(Integer deployment_type_id) {
Integer responseLastId = it_tableDAO.retrieveLastIdInTable(deployment_type_id);
return responseLastId;
}
it_tableDAO.java:
#Transactional
public List<EntityResponse> addData(Integer deployment_type_id,
Integer template_id,
Integer originator_id,
String filename,
Long user_id,
String username,
String[][] data) {
List<ColumnsNameModel> columnsName = getColumnsNameForDeploymentType(template_id);
List<EntityResponse> newRows = new ArrayList<EntityResponse>();
String tableName = getTableNameForDeploymentType(deployment_type_id);
String primaryKeyItTable = getPrimaryKeyItTableQuery(tableName);
// int columnsCountToItTable = getColumnsNameToItTable(columnsName, data);
for (int i = 1; i < data.length; i++) {
String INSERT_IT_TABLE_QUERY_part2 = "";
String updateFieldsOnConflict = "";
INSERT_IT_TABLE_QUERY = "INSERT INTO kddb." + tableName + " (";
for (int j = 0; j < data[0].length; j++) {
String column = "";
for (ColumnsNameModel columnName: columnsName) {
if (Objects.equals(columnName.getSource_field_name(), data[0][j]) ) {
column = columnName.getField_name_it_table();
if (j == 0 ) {
INSERT_IT_TABLE_QUERY += column;
updateFieldsOnConflict += column + "=EXCLUDED." + column;
}
else {
INSERT_IT_TABLE_QUERY += ", " + column;
updateFieldsOnConflict += ", " + column + "=EXCLUDED." + column;
}
INSERT_IT_TABLE_QUERY_part2 += ConcatinateToQuery(data[i][j], j);
}
}
}
updateFieldsOnConflict += ", import_user_id=EXCLUDED.import_user_id"+
", import_date=EXCLUDED.import_date"+
", import_file=EXCLUDED.import_file";
INSERT_IT_TABLE_QUERY += ", import_user_id, import_date, import_file)\n VALUES (";
INSERT_IT_TABLE_QUERY += INSERT_IT_TABLE_QUERY_part2;
INSERT_IT_TABLE_QUERY += ", " + user_id + ", \'" + new java.sql.Timestamp(new java.util.Date().getTime()) + "\', \'"
+ filename + "\'";
String uniqueKey = getUniqueKeyItTableQuery(tableName);
if (!Objects.equals(uniqueKey, null)) {
INSERT_IT_TABLE_QUERY += ") \n ON CONFLICT (" + uniqueKey + ") DO UPDATE SET \n" + updateFieldsOnConflict;
}
else {
INSERT_IT_TABLE_QUERY += ") \n ON CONFLICT (" + primaryKeyItTable + ") DO UPDATE SET \n" + updateFieldsOnConflict;
}
GeneratedKeyHolder holder = new GeneratedKeyHolder();
try {
jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(INSERT_IT_TABLE_QUERY, Statement.RETURN_GENERATED_KEYS);
return statement;
}
}, holder);
GeneratedKeyHolder holder = new GeneratedKeyHolder();
try {
jdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement statement = con.prepareStatement(INSERT_IT_TABLE_QUERY, Statement.RETURN_GENERATED_KEYS);
return statement;
}
}, holder);
} catch (Exception e) {
/* ============ THIS STATEMENT NOT UPDATE THE TABLE */
import_sessionsDAO.updateStatusOfImport_session(false, username, deployment_type_id, filename);
logger.info("++++++++++++++++++++++++++++++++++++++++");
}
/* some another actions */
return newRows;
}
import_sessionsDAO.java:
private static String UPDATE_STATUS_OF_IMPORT_SESSION =
"\n UPDATE kddb.import_sessions SET running_status = ? \n" +
" WHERE username = ? AND deployment_type_id = ? AND \n" +
" filename = ?; ";
public void updateStatusOfImport_session(Boolean running_status, String username, Integer deployment_type_id, String filename) {
logger.info(UPDATE_STATUS_OF_IMPORT_SESSION);
jdbcTemplate.update(UPDATE_STATUS_OF_IMPORT_SESSION,
running_status,
username,
deployment_type_id,
filename);
logger.info("Successfully update a status (set {}) of record with parameters: username={} deployment_type_id={} filename={}",
running_status,
username,
deployment_type_id,
filename);
}
I am fetching data from file using filestream and importing this data into oracle tables. I have column 'FT__FIRST' which is Date data type in oracle table and where i only need date values to be inserted and ignore other values. From file the date is coming in format 'YYYYMMDD'. In future if there is other values coming from file rather than Date datatype for this column and if it tries to insert into oracle table then the java code might throw an error as literal string does not match.
So to avoid this issue i want to modify my java code such that it can take only insert date format value and ignore other values. Currently i am handling only specific string from file which i know and ignoring it as they are not date format..
Java uses classes DateTimeformatter but dont know how to use it in my code..
private String createUpdateTableSql(String line, String tableName, String dateFormat, List<ColumnData> columnData) {
List<String> data = Splitter.on("|").trimResults().splitToList(line);
String ftFirst = "";
String tr = "";
String pds = "";
for (int i = 0; i < columnData.size(); i++) {
if(columnData.get(i) == null || "N.A.".equalsIgnoreCase(data.get(i)) || "N.A".equalsIgnoreCase(data.get(i)) || "UNKNOWN".equalsIgnoreCase(data.get(i))) {
continue;
}
if ("FT_FIRST".equalsIgnoreCase(columnData.get(i).getName().trim())) {
ftFirst = data.get(i);
}
if ("TR".equalsIgnoreCase(columnData.get(i).getName().trim())) {
tr = data.get(i);
}
if ("P_S_SOURCE".equalsIgnoreCase(columnData.get(i).getName().trim())) {
pds = data.get(i);
}
}
return "UPDATE " + tableName + " " +
"SET FT_FIRST=to_date('" + ftFirst + "','YYYYMMDD')" +
" WHERE TR='" + ticker +
"' AND P_S_SOURCE='" + pds + "'";
}
When you read data from file, you could parse the date field to date object like below:
// NEW CODE
private Date getDateValue(String sDate, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return
sdf.parse(format);
} catch (ParseException ignored) {
// TODO: Log this exception return null;
}
}
As you can see, you are parsing a string to date with an expected format yyyyMMdd (YYYYMMDD on oracle)
If parsing fails (value field does not containts the expected format) you can add the logic as you want on catch clausule or ignore error and let value as null.
Your code will be like this:
private String createUpdateTableSql(String line, String tableName, String dateFormat, List<ColumnData> columnData) {
List<String> data = Splitter.on("|").trimResults().splitToList(line);
String futNoticeFirst = "";
String ticker = "";
String pds = "";
for (int i = 0; i < columnData.size(); i++) {
if (columnData.get(i) == null || "N.A.".equalsIgnoreCase(data.get(i)) || "N.A".equalsIgnoreCase(data.get(i)) || "UNKNOWN".equalsIgnoreCase(data.get(i))) {
continue;
}
if ("FUT_NOTICE_FIRST".equalsIgnoreCase(columnData.get(i).getName().trim())) {
futNoticeFirst = getDateValue(data.get(i), 'yyyyMMdd');
}
if ("TICKER".equalsIgnoreCase(columnData.get(i).getName().trim())) {
ticker = data.get(i);
}
if ("PARSEKYABLE_DES_SOURCE".equalsIgnoreCase(columnData.get(i).getName().trim())) {
pds = data.get(i);
}
}
return "UPDATE " + tableName + " " +
"SET FUT_NOTICE_FIRST= " + futNoticeFirst +
" WHERE TICKER='" + ticker +
"' AND PARSEKYABLE_DES_SOURCE='" + pds + "'";
}
// NEW CODE
private Date getDateValue(String sDate, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
return
sdf.parse(format);
} catch (ParseException ignored) {
// TODO: Log this exception
return null;
}
}
I create this code for get column name in sql databases. But now I ant to modify above code for get all table data with column name. Then get all data and convert to jsonarray and pass. How I modify this code for get all table data with column name.
#Override
public JSONArray getarray(String sheetName) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
con.setAutoCommit(false);
PreparedStatement pstm = null;
Statement stmt = null;
//-----------------------Drop earliye table -------------------------------------------------------------
try {
String sqldrop = "select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='" + sheetName.replaceAll(" ", "_") + "'";
System.out.println(sqldrop);
PreparedStatement mypstmt = con.prepareStatement(sqldrop);
ResultSet resultSet = mypstmt.executeQuery();
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase();
Object columnValue = resultSet.getObject(i + 1).toString().replaceAll("_", " ");
// if value in DB is null, then we set it to default value
if (columnValue == null) {
columnValue = "null";
}
/*
Next if block is a hack. In case when in db we have values like price and price1 there's a bug in jdbc -
both this names are getting stored as price in ResulSet. Therefore when we store second column value,
we overwrite original value of price. To avoid that, i simply add 1 to be consistent with DB.
*/
if (obj.has(columnName)) {
columnName += "1";
}
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
mypstmt.close();
con.commit();
return jsonArray;
} catch (Exception e) {
System.out.println("There is no exist earlyer databases table!..... :( :( :( **************** " + sheetName.replaceAll(" ", "_"));
}
//----------------------------------------------------------------------------
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
Logger.getLogger(PassArrayDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("%%%%%%%%%%");
return null;
}
My target is get all data with column name and above data pass html page as a json. So if you have any method for get all data with column name is suitable for me.
// code starts here
// This method retrieves all data from a mysql table...
public void retrieveAllData( String host, String user, String pass, String query) {
JTextArea textArea = new JTextArea();
try(
Connection connection = DriverManager.getConnection( host, user, pass )
Statement statement = connection.createStatement()
ResultSet resultSet = statement.executeQuery(query)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int totalColumns = metaData.getColumnCount();
for( int i = 1; i <= totalColumns; i++ ) {
textArea.append( String.format( "%-8s\t", metaData.getColumnName(i) ) );
}
textArea.append( "\n" );
while( resultSet.next() ) {
for( int i = 1; i <= totalColumns; i++ ) {
Object object = resultSet.getObject(i).toString();
textArea.append( String.format("%-8s\t", object) );
}
textArea.append( "\n" );
}
}
}
I am trying to insert date into mysql. The field is of date type
but when I select a date from datepicker and insert it into database,it takes a random date..not getting where the problem is..
the code is as follow:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date d = null;
Date parsed = null;
try {
parsed = format.parse(request.getParameter("dt"));
System.out.println(parsed);
if (parsed != null) {
d = new java.sql.Date(parsed.getTime()); //parsed.getTime(
System.out.println(d);
} else {
d = new java.sql.Date(new Date().getTime());
}
} catch (ParseException e1) {
e1.printStackTrace();
}
String nature = request.getParameter("call_nature");
String name = request.getParameter("c_name");
String cat = request.getParameter("call").toString();
String num = request.getParameter("phone_no");
String street = request.getParameter("streetno").toString();
String rbut = request.getParameter("c_room");
String val = request.getParameter("hidd");
String zone = request.getParameter("combo1").toString();
String div = request.getParameter("combo2");
String hrs = request.getParameter("hr1");
String mns = request.getParameter("mn1");
String am = request.getParameter("ap1");
String occup = request.getParameter("occu");
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionurl = "jdbc:mysql://localhost:3306/fms";
String user = "root";
String pass = "root";
Connection con = DriverManager.getConnection(connectionurl, user, pass);
String sql = "insert into fire_reg values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement prst = con.prepareStatement(sql);
prst.setString(1, nature);
prst.setString(2, cat);
prst.setString(3, name);
prst.setString(4, num);
prst.setString(5, val);
prst.setString(6, street);
prst.setDate(7, d);
prst.setString(8, rbut);
prst.setString(9, zone);
prst.setString(10, div);
prst.setString(11, hrs);
prst.setString(12, mns);
prst.setString(13, am);
prst.setString(14, occup);
if (prst.executeUpdate() == 1) {
request.setAttribute("loc", street);
//System.out.println(street);
request.setAttribute("phone", num);
request.setAttribute("calltypee", cat);
request.setAttribute("zonee", zone);
RequestDispatcher rd = request.getRequestDispatcher("FMS14_DelhiRegMap.jsp");
rd.forward(request, response);
}
} catch (Exception e) {
System.out.println(e);
}
I am currently using these two methods to set certain text fields equal to the row currently selected in the JTable. I run into a problem though when I filter that table. When the data is filtered, the text fields are not populated with the correct data. The fields are being populated with the row data that would be in that place if there was no filter on the table. Anyone have any suggestions or another way I can bind the table fields with the text fields?
private void tblEmployeeMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tblEmployee.getSelectedRow();
String Table_click = (tblEmployee.getModel().getValueAt(row, 0).toString());
String sql = "select * from Employee where EmployeeID = " + Table_click + " ";
newDatabase.populateEmployee(sql);
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public void populateEmployee(String sql) throws Exception{
Constructor("newDatabase");
pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if(rs.next()) {
String add1 = rs.getString(1);
NewJFrame.txtEmpID.setText(add1);
String add2 = rs.getString(2);
NewJFrame.txtEmpFN.setText(add2);
String add3 = rs.getString(3);
NewJFrame.txtEmpLN.setText(add3);
String add4 = rs.getString(4);
NewJFrame.txtEmpMI.setText(add4);
String add5 = rs.getString(5);
NewJFrame.txtEmpAddress.setText(add5);
String add6 = rs.getString(6);
NewJFrame.txtEmpState.setText(add6);
String add7 = rs.getString(7);
NewJFrame.txtEmpZIP.setText(add7);
String add8 = rs.getString(8);
NewJFrame.txtEmpDOB.setText(add8);
String add9 = rs.getString(9);
NewJFrame.txtEmpHire.setText(add9);
String add10 = rs.getString(10);
NewJFrame.txtEmpTerm.setText(add10);
String add11 = rs.getString(11);
NewJFrame.txtEmpLic.setText(add11);
String add12 = rs.getString(12);
NewJFrame.txtEmpActive.setText(add12);
String add13 = rs.getString(13);
NewJFrame.txtEmpMan.setText(add13);
String add14 = rs.getString(14);
NewJFrame.txtEmpMod.setText(add14);
}
connection.close();
}