How to insert DATE using jsp - java

I have a feedback page on my site that contains name, email and comments. Here is my code on JSP and I'm using Apache Tomcat 7.0 and Oracle DB
String query = "Insert into t_comments(name, email, comments) values('"
+ realname
+ "','"
+ email
+ "','"
+ comments+"')";
This works great. But I decided to add DATEC column (data type DATE) to my table t_comments. So my query should look like
String query = "Insert into t_comments(name, email, comments,datec) values('"
+ realname
+ "','"
+ email
+ "','"
+ comments
+ "',"
+ "TO_DATE('"
+ new java.util.Date()
+ "', 'dd/mm/yyyy hh24:mi:ss'))";
And this doesn't work.
ORA-01858: a non-numeric character was found where a numeric was expected
Maybe I insert wrongly type DATE into my table. Also I have another problem. The name and comments are in Cyrillic. And when they inserted in table, they are displayed incorrect with different encoding. I have this lines in my JSP page
<%# page language='java' contentType='text/html; charset=UTF-8' pageEncoding='UTF-8'%>
So help me please solve my two problems
insert DATE to my table
insert Cyrillic words correct to my table
Thanks

Let oracle do it for you instead.
String query = "Insert into t_comments(name, email, comments,datec) values('"
+ realname
+ "','"
+ email
+ "','"
+ comments
+ "', CURRENT_TIMESTAMP)";
See this link for more info.

You should debug your code and check if a Date object toString() matches the pattern expected by Oracle.
Potentially, if you don't want to go in Arvind's way (which I think it's a good idea actually), you can format your Date using SimpleDateFormat.
You should also consider using a PreparedStatement instead of building the statement using String concatenation.

I thank all for your answers. I'm using CURRENT_TIMESTAMP to insert DATE to my table from #Arvind Sridharan and for cyrillic characters I added the following lines in my jsp
request.setCharacterEncoding("UTF-8");
realname = new String(realname.getBytes("ISO-8859-1"),"UTF8");
comments = new String(comments.getBytes("ISO-8859-1"),"UTF8");

Related

querying a view in oracle using java code with a where condition on a date field

I need to connect to a view in oracle view which contains information about certain matrix population in other tables.
The structure of the view (v_matrix) is:
PERIOD_START_TIME NOT NULL DATE,
MATRIX_TABLE VARCHAR2(20),
MATRIX_NAME VARCHAR2(20),
COMPLETION_TIME DATE
I am using a java code using jdbc to connect to the view.
The query which i Have is:
String query = "Select * from v_matrix where PERIOD_START_TIME LIKE \'2016-04-18 17:%\' AND MATRIX_TABLE = \'" + tableName + "\' AND MATRIX_NAME IN (" + inClauseStr.toString() + ")";
The problem is that the query fetches nothing while I can see around 200 records in the view with PERIOD_START_TIME in order of 17th hour on 18th April 2016.
The same query works fine in SQL Developer
I tried googling bud could not find any tutorial on how to filter records on a date field using java code.
I tried changing the query to
String query = "Select * from v_kpi_availability where TO_CHAR(PERIOD_START_TIME,\'YYYY-MM-DD HH24:MI:SS\') LIKE \'2016-04-18 17:%\' AND KPI_TABLE = \'" + tableName + "\' AND KPI_NAME IN (" + inClauseStr.toString() + ")";
But the query still does not fetch any records
PS: The database is Oracle 11g (11.2.0.4)
Surprising the code works in pre-prod environment with the following query:
String query = "Select * from v_kpi_availability where TO_CHAR(PERIOD_START_TIME,\'YYYY-MM-DD HH24:MI:SS\') LIKE \'2016-04-18 17:%\' AND KPI_TABLE = \'" + tableName + "\' AND KPI_NAME IN (" + inClauseStr.toString() + ")";
The reason its not working in lab because lab is on Oracle 10g where the implementation of date is a bit different.

Inserting String as datetime2(0) into SQL Server 2012 using JDBC causes error

I gather data from an external source and wish to insert it into my SQL Server 2012 database. When I attempt to insert a String, formatted as follows: "YYYY-MM-DD hh:mm:ss", which complies with the documentation., it doesn't go quite as I want to.
For clarification, the first column of my table is of type datetime2(0).
Upon executing the following code
insertData() {
...
insert.execute("INSERT INTO [LindTrading].[dbo].[Bloomberg]" +
" VALUES" +
"(" +
trade.getTimestamp() + " ," +
trade.getAmount() + "," +
trade.getPrice() + "," +
trade.getTicker() +
")");
...
}
An example of a timestamp is "2014-07-22 00:04:08".
I get the following error:
(...).SQLServerException: Incorrect syntax near '00'.
Also, getTicker() returns a string such as "CF US EQUITY", and the spaces surrounding US seem to cause similar problems, when I attempt to insert into a varchar(25) column.
What am I doing wrong?
The string containing the datetime should be within apostrophes, like
'2014-07-23 12:00:00'
And not only
2014-07-23 12:00:00
Is this the case?

How to Alter table using JOOQ?

Previously I was working with statement but I need to convert it with JOOQ
Statement dboSt = null;
dboSt = dboConn.createStatement();
I need to know how to change my below lines in JOOQ.
dboSt.executeUpdate("alter login \"" + UserId + "\" with password='" + NewPassword + "'");
dboSt.executeUpdate("alter login \"" + UserId + "\" with password='" + NewPassword + "' old_password='" + OldPassword
+ "'");
Is there any solution to convert it?
jOOQ doesn't support typesafe DDL (yet). It's been on the roadmap for a while: #883
In the mean time, you can execute plain SQL statements using jOOQ directly, as such:
DSLContext ctx = DSL.using(configuration);
// As before, manually inlining arguments:
ctx.execute("alter login \""+UserId+"\" with password='"+NewPassword+"'");
// Better, letting jOOQ do the string escaping for you, preventing
// syntax errors and SQL injection vulnerabilities:
ctx.execute("alter login {0} with password = {1}",
DSL.name(UserId), // org.jooq.Name is rendered with quotes in most DBs
DSL.inline(NewPassword) // org.jooq.Param is inlined as a (string) literal
);

Insert into database a scraped page containing double quotes with MySQL and Java

Imagine my page has a bunch of sections looking something like this (example page):
<div class="content">
</div>
My goal is to scrape the entire page into a MySQL DB entry. I currently do this like so:
//Declare SQL statement
String sql = "INSERT into rns " +
"(rns_pub_date, rns_headline, rns_link, rns_fulltext, constituent_id) values (\""+
rns.getRnsPubDate() + "\",\"" +
rns.getRnsHeadline() + "\",\"" +
rns.getRnsLink() + "\",\"" +
rns.getRnsFullText() + "\",\"" +
"(select constituent_id from constituent where constituent_name = " + rns.getRnsConstituentName() + "\")";
//SQL Statement Debug
Log.d(CLASS_NAME, "createRns. sqlStatement: " + sql);
//Initialize insertValues
insertValues = connect.prepareStatement(sql);
However, this falls over because there are multiple " marks in the page.
I can see a few options:
Escape the characters like this: '\"'
Replace the characters with: '"'
Remove all non-relevant data (the HTML) and save only the relevant data to the DB
I realise that there's also best practice with regards to preventing SQL injection. However this is a standalone system, so for the moment isn't an issue. Having said that if any answer can explain how to prevent that, I would prefer to implement that instead.
Edit 1:
Following on from #chrylis comment. This is what I have:
//Insert values into variables
String rns_pub_date = rns.getRnsPubDate();
String rns_headline = rns.getRnsHeadline();
String rns_link = rns.getRnsLink();
String rns_fulltext = rns.getRnsFullText();
String rns_constituent_name = rns.getRnsConstituentName();
//Prepare the SQL string
String sql = "INSERT into rns (rns_pub_date, rns_headline, rns_link, rns_fulltext,constituent_id) VALUES" + "(?,?,?,?,(select constituent_id from constituent where constituent_name = \"" + rns.getRnsConstituentName() + "\")";
//Prepare the statement
PreparedStatement prest = connect.prepareStatement(sql);
prest.setString(1, rns_pub_date);
prest.setString(2, rns_headline);
prest.setString(3, rns_link);
prest.setString(4, rns_fulltext);
prest.setString(5, rns_constituent_name);
However it provides this error:
Parameter index out of range (5 > number of parameters, which is 4).
Edit 2:
The insert was fixed by removing the escaped double quotes for the 5th parameter:
String sql = "INSERT into rns (rns_pub_date, rns_headline, rns_link, rns_fulltext, constituent_id) VALUES" + "(?,?,?,?,(select constituent_id from constituent where constituent_name = ?))";
Use PreparedStatement, there will be no need for escaping. Usage example is in API
It's not only a bad practice because of SQL injection, it's slow and inefficient, too, and has problems with quote characters. Use a parameterized query.

How to escape " ' " in sql

Hi I am searching for a name combination in database. I am passing the combination as follows
"firstName='" + firstName + "'", "middleName='" + middleName + "'", "lastName='" + lastName + "'"
This works fine. But the problem comes where there are some " ' " in names how can i rectify it? eg: Johns' or Jerry's etc causes exception
use preparedStatement it is easy for you
ps.executeUpdate("INSERT INTO tb_name values(?,?) WHERE id=?");
ps.setString(1,firstName);
ps.setString(2,middleName);
ps.setInt(3,id);
ps.execute();
At least for MySQL, you have to put another ' before:
INSERT INTO table (column) VALUES ('this isn''t it');
If you're using Hibernate, you should use like this:
Query query = session.createQuery("from Something s where s.firstName = :firstName and s.middleName = :middleName and s.lastName = :lastName");
query.setString("firstName", firstName);
query.setString("middleName", middleName);
query.setString("lastName", lastName);
List<?> list = query.list();
Hope this can help you!
You can see more at here and here
String firstName="X";
String middleName="Y";
String lastName="Z";
"firstName='" + firstName + "',middleName='" + middleName + "',lastName='" + lastName + "'";
You can use this to get output as
firstName='X',middleName='Y',lastName='Z'
You can ignore sinqle quotation characters (') in SQL by escaping them with a backslash \'.
Try this:
firstName = firstName.replace("'" , "''");
Use PreparedStatement instead , you would be better with that.
I guess the following also works (at least for MySQL):
SELECT login FROM usertable WHERE lastname="O'Neil";

Categories

Resources