I am trying to update the records in database according to data read from an Excel sheet. I have more than 50 columns in db whose column names are stored in an array columnNames[].
I use following code to create the Sql query.
String sqlUpdate= "Update "+tableName+
" set "+columnNames[0]+"=?";
for (int i=1;i<columnCount;i++)
{
sqlUpdate= sqlUpdate+","+columnNames[i]+"=?";
}
sqlUpdate= sqlUpdate+
" where demand_id=?";
the equivalent query obtained to printing it on console is :
Update fulfillment_plan set DEMAND_ID=?,SBU=?,PROJ_DOMAIN=?,JOBCODE=?,INDENT_STATUS=?,JC_CREATED_ON=?,PROJECT_NAME=?,CUSTOMER_NAME=?,GROUP_CUSTOMER=?,US_DEMANDS=?,SUITE_NAME=?,ROLE_NAME=?,LOCATION=?,COUNTRY=?,GEO=?,AREA=?,OPEN_POS=?,PRODUCT=?,DEMAND_TYPE=?,POSITIONS_TO_FULFILL_Q4=?,FULFILLMENT_PLAN_Q4=?,TA_STATUS_Q4=?,POSITIONS_TO_FULFILL_Q3=?,FULFILLMENT_PLAN_Q3=?,TA_STATUS_Q3=?,POSITIONS_TO_FULFILL_Q2=?,FULFILLMENT_PLAN_Q2=?,TA_STATUS_Q2=?,POSITIONS_TO_FULFILL_Q1=?,FULFILLMENT_PLAN_Q1=?,TA_STATUS_Q1=?,NET_ADD_TYPE=?,ESSENTIAL_SKILL=?,SUITE_SKILLS=?,ADDITIONAL_SKILLS=?,POSITIONS_WITH_PROPOSALS=?,POSITIONS_WITHOUT_PROPOSALS=?,DEM_ST_DATE=?,OVER_DUE_STATUS=?,OVERDUE_DAYS=?,LEAD_TIME_DAYS=?,LEAD TIME BUCKET=?,DEM_END_DATE=?,CREATED_ON=?,INDENT_CREATED_ON=?,EBD=?,OPPORTUNITYID=?,LOAD_DATE=?,PROJECT_NUMBER=?,CUSTOMER_NO=?,CUSTOMER_SUB_GEO=?,DEMAND_STATUS=?,ENGAGEMENT_TYPE=?,INVOICE_TYPE=?,INDENT_CLASSIFICATIONS=?,PROJ_STAT=?,EFD_SLA=?,RM_EMP_NAME=?,MONTH=?,QUARTER=?,YEAR=?,ACCOUNT_ID=?,ACCOUNT_TEXT=?,STATUS=? where demand_id=?
Then i have set the values to the '?' and on executing the above prepared statement in am getting the "missing equal sign" error. I have been looking into it for around 3 hours now and am not able to solve it. Kindly help.
I suspect this is due to the LEAD TIME BUCKET column name, which should either have underscores (like the other column names) or be escaped somehow - the spaces within the column name are causing the error. It would be better to have underscores in order to be consistent with your other columns, and to make the SQL simpler.
(I'd also suggest adding spaces within your SQL - e.g. one after every comma - so that the SQL can be reformatted in a text editor by line-breaking on spaces, making it easier to read. I'd have more whitespace in the Java code too, but that's clearly a matter of personal/team preference.)
Related
I am trying to pass a string value which is comma separated to birt report as parameter but failing
Java code
String userlist="\"a\",\"b\",\"c\"";
task.setParameterValue("userlist", userlist);
BeforeOpen has
params["userlist"].value.join("','");
SQL Query is
select * from users where name in (?)
I have already linked data set parameter to report parameter param_1
It's always giving me empty report even though DB table has 3 users. Any advise ?
Know your tools!
In this context: You have to understand SQL and the concept of bind variables, Javascript and BIRT.
Unfortunately every single piece of code you posted is wrong (or at least incomplete).
But you are on the right track: You can modify the SQL text in the beforeOpen event of the database. I'll sketch the idea here:
In your SQL, replace the ? with a placeholder like 'IN-LIST' (such that it is valid SQL).
You should still use the bind variable in the SQL (to avoid pitfalls caused by BIRT's caching mechanism), but in an effective no-op way, e.g. "where ? is not null".
In the beforeOpen event of the data set, you can modify the SQL text:
Get the original SQL text (var query = this.queryText; IIRC).
Split your report parameter into the individual search terms. How exactly to do this depends on your input format. In your example, you are using " around your search terms, which looks overly complicated, unless individual search terms may contain commas. You should now have a list of your search strings, e.g. ["a", "b", "c"].
Convert each term into a valid SQL string literal. Beware of SQL injection attacks, so carefully escape characters like single-quotes! You should now have a list of valid SQL string literals, e.g. ["'a"', "'b'", "'c'"].
Join your list of SQL string literals from 3) into a single string with ", ".
You should now have a string like 'a', 'b', 'c'.
In your query, replace your placeholder string with the string from 4).
Write the modified SQL text back to the DS object: this.queryText = query;
Probably there is also an example somewhere in the mists of the internet.
If you had invested five minutes more, you should have found an existing answer here on stack overflow: How to create a BIRT dataset that accepts multiple (CSV) values that it can be used inside "IN" clause in select statement, the only difference being that you are searching for a list of strings, while that question was about a list of numbers.
because i'm convert my concoction DB to derby in netbeans
all statement happen error in it.
the error is it
java.sql.SQLSyntaxErrorException: table or view does not exist.
to solve problem must be change in all attribute and tables name
by Place it between brackets
for example
st.executeQuery("SELECT * FROM loges ");
not run its syntax error
must change to
st.executeQuery("SELECT * FROM \"loges\" ");
Then it works properly
doing this very hard,i have 137 query statement contain a lot
of tables and attribute names.
i'm doing this change because extract my project to executable desktop program
if can make this in other way will be good
If your code uses all unquoted table and column names, then your database schema should be created with unquoted names.
If you're having trouble now, then your new database was created/migrated with quoted names. Fix that, and you code will work unchanged.
Be aware that databases treats unquoted names differently, e.g. Oracle will change the names to uppercase, PostgreSQL will change the names to lowercase, and MS SQL Server will store the names as given, but will by default match them case-insensitively.
You should create the tables without double quotes, as explained in the duplicate question
I am currently writing a Java web application which interfaces with an Oracle database. I am using PreparedStatements because Hibernate would complicate things too much.
Due to a bug in the program which is writing to the database, the field I need to search for has trailing spaces written to the value. I have surrounded the value with quotation marks to demonstrate the whitespace.
"testFTP_receipt521 "
When I do a select query with SQLDeveloper, I am able to get a result when I run:
...and yfs_organization.ORGANIZATION_KEY='testFTP_receipt521';
(no whitespace)
However, when I use a PreparedStatement, I get no results when I try:
...and yfs_organization.ORGANIZATION_KEY=?");
preparedStatement.setString(1, "testFTP_receipt521");
(no whitespace)
and when I try:
...and yfs_organization.ORGANIZATION_KEY=?");
preparedStatement.setString(1, "testFTP_receipt521 ");
(with whitespace)
Are there any ways that I can query for this result with a PreparedStatement, or should I try another approach?
Thanks for all your help.
Due to a bug in the program which is writing to the database, the field I need to search for has trailing spaces
Maybe, given the circumstances, and if your version of Oracle is recent enough, you might consider adding a virtual column to your table containing the correct value?
ALTER TABLE yfs_organization ADD (
ORGANIZATION_KEY_FIXED VARCHAR(80)
GENERATED ALWAYS AS (TRIM(ORGANIZATION_KEY)) VIRTUAL
);
Then in your code, the only change will be to use the ORGANIZATION_KEY_FIXED to query the DB:
SELECT ID,ORGANIZATION_KEY_FIXED
FROM yfs_organization
WHERE ORGANIZATION_KEY_FIXED='testFTP_receipt521'
(try it on http://sqlfiddle.com/#!4/8251d/1)
This might avoid to scatter around your application the code required to work around that bug. And might ease the transition once it will be fixed.
As an added benefice, you could add index on virtual columns if you need too.
Maybe you can use it like this...
...and yfs_organization.ORGANIZATION_KEY like '%testFTP_receipt521%';
this way returns you all reg where contains 'testFTP_receipt521' independently of whitespace.
Antoher thing that i saw in your code in this part
...and yfs_organization.ORGANIZATION_KEY=?");
preparedStatement.setString(1, "testFTP_receipt521");
i thing this is the correct way
...and yfs_organization.ORGANIZATION_KEY='?'");
you need to put quotes around the criteria
If you have the ability to modify the query, you can TRIM(...) the column value and perform the comparison. For example:
...and TRIM(yfs_organization.ORGANIZATION_KEY)=?");
Hope it helps.
I'm converting (or trying to) an Ms AccessDB into derby.
When I extract the data from certain varchar / text / memo field from access they are filled with apostrophe, and mathematical symbols (percent, less than etc), and possible foreign characters
I need to keep these and I test for them so as I can use an 'escape sequence' to ensure they get put into the database.
However for now I am unable to get the data into the DB without it failing on these fields. When the SQL fails I output the SQL string, and cut and past it into ij. Then I modify just the first record, and it is always these characters that cause me grief.
I've tried to modify the strings by surrounding with "double quote marks" but that just gives a different error (stating that it has 'enounterd """ at line1 column x' which is always the first occurance of the double quote).
I haven't found a setting in derby to alter the behaviour for strings, yet. Is there one?
I have also tried to set the SQL statment to a preparedStatement then use the {call preparedStatement} again this fails also. I can't use the {escape "escape char} in a normal statment as derby just says incorrect syntax at me.
How do others manage to get user content with strange characters into a field in derby?
Do I need to change my field into a CLOB or something other than varchar / long Varchar?
Are my problems being caused by using the wrong characteset (eg iso rather UTF-8), how do I tell what it is, how to change it?
Below is a sample of the SQL insert that fails when I send it to derby (via my JAVA 'programme')
insert into S1.SORTIEDESSAI (OBS, DATEDUSORTIE, CONTREINDIC, FIN,
PDEVU, REFUS, INVDECISN, ADMIN, MOTIF_DE_LA_SORTIE, NOMVALIDEE,
DATEVALIDEE) values ('"0001/0001"' , '2007-07-15' , false , true ,
'"null"' , '"null"' , '"null"' , '"null"' , '"2. FIN DE L’ESSAI"' ,
'"DR SIMON"' , '2011-04-19' )
Note:
Actually I look at the above and notice that the order of columns names isn't good? It was OK yesterday, not sure why it would have changed? something to do with Access returning the column names in a random order from the resultSetMetaData, which would be a surprise.
for now I recomend any further answers to hold off whilst I sort this problem out, OK solved that problem, do I need to set another question about this behaviour....
Back to the main thread...
Ok as you can see on my SQL statement I have wrapped any varchar fields in double quotes. This always fails (even directly through ij). help help help...
I'm not quite sure what your question is, but in general you can input these characters by using a PreparedStatement of the form: INSERT INTO tablename (columnname) values (?), and then using the PreparedStatement.setString() method to supply your character data for that column.
I have a field with varchar(100) in mysql, I want to store first 100 characters because my data length is 200 characters(ignore last 100 character).I doesn't want to change my source code. Which is possible in MS-Access and MS Server but I want to do this in mysql.
I am applying this in java with hibernate, means I am not writing insertion code for this. Here I am just using save() method and its throwing "Large data".
I have got Exception-
Caused by: java.sql.BatchUpdateException: Data truncation: Data too long for column 'FBUrl' at row 1
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1527)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1065)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195)
glb.chatmeter.exception.AdException: Could not Save Facebook page Data.
Note: An hour after the below, the question was edited with a substantial change. This answer answered the question as it was originally, but doesn't address the edited version.
You can use substring:
INSERT INTO MyTable (Myfield) values (SUBSTRING('long string', 1, 100))
The pos parameter starts at 1 (oddly), and it's okay if the len parameter is larger than the length of what you're actually inserting.
You can use SUBSTRING() to trim inserts:
INSERT INTO table (column) VALUES (SUBSTRING("your data...", 1, 100))
try this
SELECT INSERT('your string', 0, 100, '');
REFERENCE
The only way to do it without changing the source code is to fiddle with the configuration of the MySQL server. More specifically, the sql_mode variable:
http://dev.mysql.com/doc/refman/5.1/en/server-sql-mode.html
I believe you have to set STRICT_TRANS_TABLES:
For STRICT_TRANS_TABLES, MySQL
converts an invalid value to the
closest valid value for the column and
insert the adjusted value. If a value
is missing, MySQL inserts the implicit
default value for the column data
type. In either case, MySQL generates
a warning rather than an error and
continues processing the statement.
Implicit defaults are described in
Section 10.1.4, “Data Type Default
Values”.
However, it's important to note that this setting will affect many other things. The only reason I see not to change the source code is that you don't have access to it, and in such case you can probably just enlarge the DB column.