Help for prepared statement
hi,
I want to usefollowing sql statement by preparedstatment
select * from tbl_PreServiceManager where (trunc(Activation_Date+30)<trunc(Sysdate) or counter > 0) and CPS<>'FDE'";{code}
to convert it to prepared statement i did following
{code}String query="select * from tbl_Pre where (trunc(Activation_Date+30)<trunc(Sysdate) or counter >?) and CPS<>?;"
pstmt = conn.prepareStatement( query );
pstmt.setInt(1,0);
pstmt.setString(2,"FDE");
rset = pstmt.executeQuery();
{code}
but how i manage activation_date with trunc function, infact activation_date field is datetime and i only want to campare date.
Thanks
EG:
datepart (dp):
dd -> day -> 1-31
dy -> day of year -> 1-366
hh -> hour -> 0-23
mi -> minute -> 0-59
mm -> month -> 1-12
qq -> quarter -> 1-4
ss -> second -> 0-59
ms -> millisecond -> 0-999
wk -> week -> 0-53
dw -> weekday -> 1-7(Sun - Mon)
yy -> year -> 1753
SELECT DATEPART(yy,GETDATE()),
DATEPART(mm,GETDATE()),
DATEPART(dy,GETDATE())Output
2008 | 07 | 28
Similar Messages
-
XML SQL format for Prepared statements in batch mode
Hi
I want to use the batch mode in JDBC adapter for inserting huge volume of records with better performance.
so i need to execute the prepared statements in one batch. Is the XML SQL format for prepared statements below correct ?to<root>
<stmt>
<Customers action="SQL_DML">
<access> INSERT INTO Customers (CompanyName,Address,CustomerID) VALUES($NAME$,$ADDRESS$,$KEYFIELD$)
</access>
<key>
<NAME>IBM</NAME>
<ADDRESS>Street 3 </ADDRESS>
<KEYFIELD>CO</KEYFIELD>
</key>
<key>
<NAME>PWC</NAME>
<ADDRESS>Street 4 </ADDRESS>
<KEYFIELD>NO</KEYFIELD>
</key>
</Customers>
</stmt>
</root>
Please adviseHello Experts
Please throw some light on the above question.
Thanks in advance. -
Startup class for prepared statement cache
Hi
we are using weblogic 7.0 sp1 . As clearcacheparamters method is not available
with this version ,we have written a startup class to cache the preparedstaments
that we need ,even then these statements are not getting cached .we have observed
the oracle trace,it is parsing the prepared statement each time we make a call.Can
anyone clarify where iam doing wrong and suggest me a way to cache the prepared
statements we wanted.
my sample startup class looks like this
Collection connections = new ArrayList();
int conCount = 0;
Connection con =null;
PreparedStatement prep1=null;
PreparedStatement prep2=null;
PreparedStatement prep3=null;
while(true)
try
con = SQLConnection.getConnection();
connections.add(con);
prep1 = con.prepareStatement(sql1);
prep2 = con.prepareStatement(sql2);
prep 3 = con.prepareStatement(sql3);
conCount++;
catch (SQLException e)
System.out.println("exception SQLException "+e.getMessage());
break;
catch (IOException e)
System.out.println("******StartUp Connections got ---> "+conCount);
try
Iterator connectionIt = connections.iterator();
while(connectionIt.hasNext())
con = (Connection) connectionIt.next();
con.close();
catch (SQLException e)
we cant upgrade to sp3 immediately ,so please provide a solution for weblogic
7.0 sp1.
Thanks & Regards
RangaHi
we are using weblogic 7.0 sp1 . As clearcacheparamters method is not available
with this version ,we have written a startup class to cache the preparedstaments
that we need ,even then these statements are not getting cached .we have observed
the oracle trace,it is parsing the prepared statement each time we make a call.Can
anyone clarify where iam doing wrong and suggest me a way to cache the prepared
statements we wanted.
my sample startup class looks like this
Collection connections = new ArrayList();
int conCount = 0;
Connection con =null;
PreparedStatement prep1=null;
PreparedStatement prep2=null;
PreparedStatement prep3=null;
while(true)
try
con = SQLConnection.getConnection();
connections.add(con);
prep1 = con.prepareStatement(sql1);
prep2 = con.prepareStatement(sql2);
prep 3 = con.prepareStatement(sql3);
conCount++;
catch (SQLException e)
System.out.println("exception SQLException "+e.getMessage());
break;
catch (IOException e)
System.out.println("******StartUp Connections got ---> "+conCount);
try
Iterator connectionIt = connections.iterator();
while(connectionIt.hasNext())
con = (Connection) connectionIt.next();
con.close();
catch (SQLException e)
we cant upgrade to sp3 immediately ,so please provide a solution for weblogic
7.0 sp1.
Thanks & Regards
Ranga -
Hi,
Need help to write sql statement.
create table t_dt ( dt_start date, dt_end date, amount number);
insert into t_dt values('1-Jan-10','10-Feb-10',12);
insert into t_dt values('11-Feb-10','10-Mar-10',10);
insert into t_dt values('11-Mar-10','20-Apr-10',8);
insert into t_dt values('21-Apr-10','28-Jun-10',10);
insert into t_dt values('29-Jun-10','20-Sep-10',10);
insert into t_dt values('21-Sep-10','10-Oct-10',10);
insert into t_dt values('11-Oct-10','31-Dec-10',8);
insert into t_dt values('1-Jan-11','10-Feb-11',8);
insert into t_dt values('11-Feb-11','10-Mar-11',7);
insert into t_dt values('11-Mar-11','20-Apr-11',6);
insert into t_dt values('21-Apr-11','28-Jun-11',6);
insert into t_dt values('29-Jun-11','20-Sep-11',6);
insert into t_dt values('21-Sep-11','10-Oct-11',4);
insert into t_dt values('11-Oct-11','31-Dec-11',8);
Result should be like below..
dt_start dt_end Amount
1-Jan-10 10-Feb-10 12
11-Feb-10 10-Mar-10 10
11-Mar-10 20-Apr-10 8
21-Apr-10 10-Oct-10 10
11-Oct-10 10-Feb-11 8
11-Feb-11 10-Mar-11 7
11-Mar-11 20-Sep-11 6
21-Sep-11 10-Oct-11 4
11-Oct-11 31-Dec-11 8
Just to explain the example, take a row with start date as 21-Apr-10 in the above insert statements, since it has the same amount for next two rows (i.e. with start date '29-Jun-10' and '21-Sep-10') these 3 rows should be converted to represent only 1 row in the result and the start date and end date should be changed per the result shown above.
Thanks.Hello
I think this gives yuo what you need....
SELECT
MIN(dt_start),
MAX(dt_end),
amount
FROM
( SELECT
dt_start,
dt_end,
MAX(marker) OVER(ORDER BY dt_start) marker,
amount
FROM
Select
dt_start,
dt_end,
amount,
CASE
WHEN LAG(amount) OVER(ORDER BY dt_start) <> amount THEN
ROW_NUMBER() OVER(ORDER BY dt_start)
END marker
from t_dt
GROUP BY
amount,
marker
order by
MIN(dt_start)
MIN(DT_START) MAX(DT_END) AMOUNT
01-JAN-2010 00:00:00 10-FEB-2010 00:00:00 12
11-FEB-2010 00:00:00 10-MAR-2010 00:00:00 10
11-MAR-2010 00:00:00 20-APR-2010 00:00:00 8
21-APR-2010 00:00:00 10-OCT-2010 00:00:00 10
11-OCT-2010 00:00:00 10-FEB-2011 00:00:00 8
11-FEB-2011 00:00:00 10-MAR-2011 00:00:00 7
11-MAR-2011 00:00:00 20-SEP-2011 00:00:00 6
21-SEP-2011 00:00:00 10-OCT-2011 00:00:00 4
11-OCT-2011 00:00:00 31-DEC-2011 00:00:00 8
9 rows selected.HTH
David
Edited by: Bravid on Feb 23, 2012 12:08 PM
Beaten to it by Frank! :-) -
Help for merge statement?
I have a problem in Merge statement. My merge statement is following:
MERGE INTO hoadon hd
USING (
SELECT m.ma_ttoan, t.ma_ttoan ma_kh
FROM tai_anhxa_makh t
INNER JOIN hoadon m on t.ma_kh = m.ma_ttoan
WHERE m.thang_nam = '200908' and m.ma_ttoan not like 'DLC%' and t.ma_ttoan IS NOT NULL
GROUP BY m.ma_ttoan, t.ma_ttoan
) m ON (hd.ma_ttoan = m.ma_kh)
WHEN MATCHED THEN
UPDATE SET ma_ttoan = m.ma_ttoan
WHEN NOT MATCHED THEN
INSERT (thang_nam, ma_ttoan) VALUES('200908','thaodv')
After execute this query, PS/SQL show error message: "ORA-00904: hd.ma_ttoan invalid identifier"
I'm using Oracle version 9i
Can anyone help me to resolve this problem?
Thanks in advanceIn 9i you can't use the columns from the ON clause in your UPDATE part of the MERGE statement
this is invalid:
UPDATE SET ma_ttoan = m.ma_ttoanuse a different column here. -
I have a MERGE statement, I am executing it from shell script, I want to print that how many rows has been updated and Inserted.
Can any one give me some idea.
Thanks in AdvanceI want to print that how many rows has been updated and Inserted. If you really want/need to print that information, then don't use MERGE but INSERT and UPDATE statements.
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:35615502072484
http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:122741200346595110 -
Error handling in prepared statement batch
Hi,
For a prepared statement batch, it is not possible to know which operation failed. ... You should always perform a ROLLBACK operation in this situation.
For a generic statement batch or callable statement batch, the update counts array is only a partial array containing the actual update counts up to the point of the error. ... You can either commit or roll back the successful operations in this situation, as you prefer.
-- http://otn.oracle.com/docs/products/oracle9i/doc_library/release2/java.920/a96654/oraperf.htm#1056233
But, I want to skip failed operations and continue to excecute the remains of the batch, also, I want to improve application performance, what should I do? Is there any choice?
Best Regards,
Kevin ZhaoAccording to the Oracle docs these are not the only possible values:
Oracle9i JDBC Developer's Guide and Reference
Release 2 (9.2) chapter 12
Performance Extensions
"For a prepared statement batch, it is not possible to know which operation failed. The array has one element for each operation in the batch, and each element has a value of -3. According to the JDBC 2.0 specification, a value of -3 indicates that an operation did not complete successfully. In this case, it was presumably just one operation that actually failed, but because the JDBC driver does not know which operation that was, it labels all the batched operations as failures."
It goes on to say that for a generic statement batch it is possible to know which failed. I would like to know if similar functionality will be available for prepared statement batches in the future. -
Help changing to prepared statements for mysqli
I am trying to change previously working php pages from mysql to mysqli using prepared statements.
I am having problems with an error message.
Basically the page I have just changed produces a set of database results depending on list menu and check box criteria from user input. I run 2 queries, one to find the total number of records, and the other to retrieve the required subset for pagination. All works fine. However if there are no actual results found from the requested input my php script then uses an includes file which basically runs the same 2 queries but with the user criteria narrowed down so that similar options are presented to the user. This is where my problem lies, for some unknown to me reason the second set of queries is producing no results and an error:
'Attempt to read a row while there is no result set associated with the statement'
If I run the second set of queries without running the first set then the second set works fine so I know that it is not the statements themselves but something in my new code. How can the first set of queries be affecting the results of the second set?
Here is the code below which produces the first 2 queries that work, and below it the same code for the second 2 queries (which is from an 'Includes' file and is the same code exactly except the EXPECTED parameters $expected have been narrowed down in the expected array and list of params for binding).
//list of possible field input by user
$expected = array('location' => 'text',
'type' => 'text',
'beds' => 'text',
'price' => 'text',
'nbuild' => 'int',
'resale' => 'int',
'coastal' => 'int',
'seaview' => 'int',
'rural' => 'int',
'golf' => 'int',
'ppool' => 'int',
'comp' => 'int',
'garden' => 'int',
'terrace' => 'int',
'aircon' => 'int',
'heating' => 'int',
'garage' => 'int',
'telephone' => 'int',
'furnished' => 'int',
'internet' => 'int',
'dpaid' => 'int',
'propid' => 'text');
define('SHOWMAX', 10);
// prepare SQL to get total records
$getTotal = 'SELECT COUNT(*) FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ';
// Set a flag to indicate whether the query has a WHERE clause
$where = false;
// Loop through the associatiave array of expected search values
foreach ($expected as $var => $type) {
if (isset($_GET[$var])) {
$value = trim(urldecode($_GET[$var]));
if (!empty($value)) {
// Check if the value begins with > or <
// If so, use it as the operator, and extract the value
if ($value[0] == '>' || $value[0] == '<') {
$operator = $value[0];
$value = ltrim(substr($value, 1));
} elseif (strtolower($type) != 'like') {
$operator = '=';
// Check if the WHERE clause has been added yet
if ($where) {
$getTotal .= ' AND ';
} else {
$getTotal .= ' WHERE ';
$where = true;
// Build the SQL query using the right operator and data type
$type = strtolower($type);
switch($type) {
case 'like':
$getTotal .= "`$var` LIKE ? ";
break;
case 'int':
case 'double':
case 'date':
$getTotal .= "`$var` $operator ? ";
break;
default:
$getTotal .= "`$var` = ? ";
$getTotal .= ' ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC';
$stmt = $conn->stmt_init();
if ($stmt->prepare($getTotal)) {
$params = array($_GET['location'], $_GET['type'], $_GET['beds'], $_GET['price'], $_GET['nbuild'], $_GET['resale'], $_GET['coastal'], $_GET['seaview'], $_GET['rural'], $_GET['golf'], $_GET['ppool'], $_GET['comp'], $_GET['garden'], $_GET['terrace'],
$_GET['aircon'], $_GET['heating'], $_GET['garage'], $_GET['telephone'], $_GET['furnished'], $_GET['internet'], $_GET['dpaid'], $_GET['propid']);
$params = array_filter($params);
$params = array_values($params);
if (!empty($params)) {
$types = '';
foreach($params as $param) {
// set param type
if (is_string($param)) {
$types .= 's'; // strings
} else if (is_int($param)) {
$types .= 'i'; // integer
} else if (is_float($param)) {
$types .= 'd'; // double
} else {
$types .= 'b'; // default: blob and unknown types
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
call_user_func_array(array(&$stmt,'bind_param'),$bind_names);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($total);
$stmt->fetch();
// sort paging
$totalRecords = $total;
$stmt->free_result();
$stmt->close();
// check that there is at least 1 result and if there is do the second part of the search
// if there is no result then I skip this second bit of code
if($totalRecords > '0') {
// check current page
if (isset($_GET['curPage'])) {
$curPage = $_GET['curPage'];
} else {
$curPage = 0;
// calculate the start row of the subset
$startRow = $curPage * SHOWMAX;
$sql = "SELECT DISTINCT detailsid, trueprice, reduced, offers, `desc`, `propid`, `bathrooms`, `location`, `type`, `price`, `beds`, photossale.photo1, newloctable.newloc, typetable.style, bedtable.`number` FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ";
// Set a flag to indicate whether the query has a WHERE clause
$where = false;
// Loop through the associatiave array of expected search values
foreach ($expected as $var => $type) {
if (isset($_GET[$var])) {
$value = trim(urldecode($_GET[$var]));
if (!empty($value)) {
// Check if the value begins with > or <
// If so, use it as the operator, and extract the value
if ($value[0] == '>' || $value[0] == '<') {
$operator = $value[0];
$value = ltrim(substr($value, 1));
} elseif (strtolower($type) != 'like') {
$operator = '=';
// Check if the WHERE clause has been added yet
if ($where) {
$sql .= ' AND ';
} else {
$sql .= ' WHERE ';
$where = true;
// Build the SQL query using the right operator and data type
$type = strtolower($type);
switch($type) {
case 'like':
$sql .= "`$var` LIKE ? ";
break;
case 'int':
case 'double':
case 'date':
$sql .= "`$var` $operator ? ";
break;
default:
$sql .= "`$var` = ? ";
$sql .= " ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC LIMIT $startRow," . SHOWMAX;
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$nextparams = $params;
if (!empty($nextparams)) {
$nexttypes = '';
foreach($nextparams as $nextparam) {
// set param type
if (is_string($nextparam)) {
$nexttypes .= 's'; // strings
} else if (is_int($nextparam)) {
$nexttypes .= 'i'; // integer
} else if (is_float($nextparam)) {
$nexttypes .= 'd'; // double
} else {
$nexttypes .= 'b'; // default: blob and unknown types
$newbind_names[] = $nexttypes;
for ($i=0; $i<count($nextparams);$i++) {
$newbind_name = 'bind' . $i;
$$newbind_name = $nextparams[$i];
$newbind_names[] = &$$newbind_name;
call_user_func_array(array(&$stmt,'bind_param'),$newbind_names);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($detailsid, $trueprice, $reduced, $offers, $desc, $propid, $bathrooms, $location, $type, $price, $beds, $photo1, $newloc, $style, $bednumber);
$numRows = $stmt->num_rows;
If a result was found in the part that checks the numbers of records then the second query is run and displayed using : while ($stmt->fetch()) { ...... to display the results and then I use $stmt->free_result();
$stmt->close();
All fine no problems.
If the first query did not find a result then the second query is skipped and instead the script then uses a php includes file with exactly the same script as above except the expected params are narrowed as below: THIS IS WHEN I GET NO RESULTS – when I do expect to get a result) AND AN ERROR OF :
Attempt to read a row while there is no result set associated with the statement.
Yet if I run the includes file and skip the whole of the above code the code in the includes file find the result no problem. Anyway code below:
$expected = array('location' => 'text',
'type' => 'text',
'beds' => 'text',
'price' => 'text',
'dpaid' => 'int',
'propid' => 'text');
define('SHOWMAX', 10);
// prepare SQL to get total records
$getTotal = 'SELECT COUNT(*) FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ';
// Set a flag to indicate whether the query has a WHERE clause
$where = false;
// Loop through the associatiave array of expected search values
foreach ($expected as $var => $type) {
if (isset($_GET[$var])) {
$value = trim(urldecode($_GET[$var]));
if (!empty($value)) {
// Check if the value begins with > or <
// If so, use it as the operator, and extract the value
if ($value[0] == '>' || $value[0] == '<') {
$operator = $value[0];
$value = ltrim(substr($value, 1));
} elseif (strtolower($type) != 'like') {
$operator = '=';
// Check if the WHERE clause has been added yet
if ($where) {
$getTotal .= ' AND ';
} else {
$getTotal .= ' WHERE ';
$where = true;
// Build the SQL query using the right operator and data type
$type = strtolower($type);
switch($type) {
case 'like':
$getTotal .= "`$var` LIKE ? ";
break;
case 'int':
case 'double':
case 'date':
$getTotal .= "`$var` $operator ? ";
break;
default:
$getTotal .= "`$var` = ? ";
$getTotal .= ' ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC';
$stmt = $conn->stmt_init();
if ($stmt->prepare($getTotal)) {
$params = array($_GET['location'], $_GET['type'], $_GET['beds'], $_GET['price'], $_GET['dpaid'], $_GET['propid']);
$params = array_filter($params);
$params = array_values($params);
if (!empty($params)) {
$types = '';
foreach($params as $param) {
// set param type
if (is_string($param)) {
$types .= 's'; // strings
} else if (is_int($param)) {
$types .= 'i'; // integer
} else if (is_float($param)) {
$types .= 'd'; // double
} else {
$types .= 'b'; // default: blob and unknown types
$bind_names[] = $types;
for ($i=0; $i<count($params);$i++) {
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
call_user_func_array(array(&$stmt,'bind_param'),$bind_names);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($total);
$stmt->fetch();
// sort paging
$totalRecords2 = $total;
echo $stmt->error;
$stmt->free_result();
$stmt->close();
// there is a result get the subset
if($totalRecords2 > '0') {
// check current page
if (isset($_GET['curPage'])) {
$curPage = $_GET['curPage'];
} else {
$curPage = 0;
// calculate the start row of the subset
$startRow = $curPage * SHOWMAX;
$sql = "SELECT DISTINCT detailsid, trueprice, reduced, offers, `desc`, `propid`, `bathrooms`, `location`, `type`, `price`, `beds`, photossale.photo1, newloctable.newloc, typetable.style, bedtable.`number` FROM detailstable JOIN newloctable ON detailstable.location=newloctable.newlocid JOIN typetable ON detailstable.type=typetable.typeid JOIN pricetable ON detailstable.price=pricetable.priceid JOIN bedtable ON detailstable.beds=bedtable.bedid JOIN photossale ON detailstable.detailsid=photossale.propsaleid ";
// Set a flag to indicate whether the query has a WHERE clause
$where = false;
// Loop through the associatiave array of expected search values
foreach ($expected as $var => $type) {
if (isset($_GET[$var])) {
$value = trim(urldecode($_GET[$var]));
if (!empty($value)) {
// Check if the value begins with > or <
// If so, use it as the operator, and extract the value
if ($value[0] == '>' || $value[0] == '<') {
$operator = $value[0];
$value = ltrim(substr($value, 1));
} elseif (strtolower($type) != 'like') {
$operator = '=';
// Check if the WHERE clause has been added yet
if ($where) {
$sql .= ' AND ';
} else {
$sql .= ' WHERE ';
$where = true;
// Build the SQL query using the right operator and data type
$type = strtolower($type);
switch($type) {
case 'like':
$sql .= "`$var` LIKE ? ";
break;
case 'int':
case 'double':
case 'date':
$sql .= "`$var` $operator ? ";
break;
default:
$sql .= "`$var` = ? ";
$sql .= " ORDER BY ABS(detailstable.trueprice), bedtable.number, detailstable.propid ASC LIMIT $startRow," . SHOWMAX;
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)) {
$nextparams = $params;
if (!empty($nextparams)) {
$nexttypes = '';
foreach($nextparams as $nextparam) {
// set param type
if (is_string($nextparam)) {
$nexttypes .= 's'; // strings
} else if (is_int($nextparam)) {
$nexttypes .= 'i'; // integer
} else if (is_float($nextparam)) {
$nexttypes .= 'd'; // double
} else {
$nexttypes .= 'b'; // default: blob and unknown types
$newbind_names[] = $nexttypes;
for ($i=0; $i<count($nextparams);$i++) {
$newbind_name = 'bind' . $i;
$$newbind_name = $nextparams[$i];
$newbind_names[] = &$$newbind_name;
call_user_func_array(array(&$stmt,'bind_param'),$newbind_names);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($detailsid, $trueprice, $reduced, $offers, $desc, $propid, $bathrooms, $location, $type, $price, $beds, $photo1, $newloc, $style, $bednumber);
$numRows = $stmt->num_rows;
Again here I would then display the results before closing and freeing the stmt or display a message to say there were no results found from the criteria. But instead I get the error message and echoing the value of $totalRecords2 is empty.
I have been pulling my hair out for days and days over this and as it is one of the first pages I am converting from mysql to mysqli I wonder if I am missing something very obvious to someone with more experience with the code. I will be very grateful for any help, thank you in advance.You have intel graphics, that means the graphics cannot be upgraded.
Welcome to the Toshiba user forums.
For those of you who do not know what a user forum is, it is a community of users who volunteer time to help other users. Anyone can participate. It's 100% voluntary.
Being super active is never a requirement -
How to use prepared statement - For Everyone Help
public String count()
int count = 0;
String fetchsize = "";
try
Connection conn = getOADBTransaction().getJdbcConnection();
Statement statement = conn.createStatement();
String Query = "select count(*) count from fnd_lookups where lookup_type like 'SAPE_BILL_TO_SHIP_TO_UPDATE'";
ResultSet resultset = statement.executeQuery(Query);
while (resultset.next())
count = (int)resultset.getInt("count");
fetchsize = ""+count;
catch(Exception e)
return fetchsize;
}Hi,
we can use prepare statement in Co....
import java.sql.PreparedStatement;
import java.sql.ResultSet;
try
PreparedStatement prpdStmt1 = am.getOADBTransaction().getJdbcConnection().prepareStatement("select full_name from per_all_people_f where person_id='"+empid+"' ");
ResultSet rs=prpdStmt1.executeQuery(); //Cursor fetch row
while(rs.next())
empname=rs.getString(1);
catch(Exception e)
System.out.println("Exception is"+e.getMessage());
t1.setValue(pageContext,empname);
Thanks
nani -
Beginner question about prepared statements...PLEASE help! :-)
First let me say thanks for the assistance. This is probably really easy to do, but I'm new to JSP and can't seem to figure it out.
I want to dynamically populate a table that shows whether a particular person has an appointment at a given date and time with a user. To do this, I want to query the MySQL database for the lastname of the person with the appointment that occurs with the user at the year, month, date, and time, in question.
THE CODE BELOW DOESN'T WORK (obviously) BUT SOMEWHAT ILLUSTRATES WHAT I'M TRYING TO ACCOMPLISH:
<%
Driver DriverTestRecordSet = (Driver)Class.forName(MM_website_DRIVER).newInstance();
Connection ConnTestRecordSet = DriverManager.getConnection(MM_website_STRING,MM_website_USERNAME,MM_website_PASSWORD);
PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='<%=(((Recordset1_data = Recordset1.getObject(user_id))==null || Recordset1.wasNull())?"":Recordset1_data)%>' AND year='<%= yy %>' AND month='<%= months[mm] %>' AND date='<%= dates[dd] %>' AND appttime='16:15:00'");
ResultSet TestRecordSet = StatementTestRecordSet.executeQuery();
boolean TestRecordSet_isEmpty = !TestRecordSet.next();
boolean TestRecordSet_hasData = !TestRecordSet_isEmpty;
Object TestRecordSet_data;
int TestRecordSet_numRows = 0;
%>
The real problem comes in the prepared statement portion. If I build the prepared statement with static values like below, EVERYTHING WORKS GREAT:
PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id='1' AND year='2002' AND month='October' AND date='31' AND appttime='16:15:00'");
But when I try to use dynamic values, everything falls apart. It's not that the values aren't defined, I use the user_id, year <%= yy %>, month <%= months[mm] %>, etc. elsewhere on the page with no problems. It's just that I can't figure out how to use these dynamic values within the prepared statement.
Thanks for reading this far and thanks in advance for the help!!!!Hi PhineasGage
You are little bit wrong in your
your preparedStatement.
Expression tag within scriptlet tag is invalid.
Whenever you are appending the statement with
expression tag, append it with "+" and remove
expression tag.
Hopefully it will work
ThanksThanks for the response!
I know that the expression tag within scriptlet tag is invalid. I just need a workaround for what I want to do.
I'm unclear what you mean by "Whenever you are appending the statement with expression tag, append it with a "+" and remove expression tag".
Could you give an example?
In the meantime, I've been trying to digest the docs on prepared statements and have changed the code to look like:
PreparedStatement StatementTestRecordSet = ConnTestRecordSet.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id= ? AND year= ? AND month= ? AND date= ? AND appttime='13:15:00'");
StatementTestRecordSet.setInt(1,1);
StatementTestRecordSet.setInt(2,2002);
StatementTestRecordSet.setString(3,"October");
StatementTestRecordSet.setInt(4,31);
Again, WITH THE STATIC VALUES, THIS WORKS FINE...but when I try to use expressions or variables like below, things don't work:
StatementTestRecordSet.setInt(2,<%= yy %>);
Obviously, I'm doing something wrong, but there has to be a way to use variables within the prepared statement.
ALSO, the values are being passed to this page via URL in the form:
samplepage?user_id=1&year=2002&month=October&date=31
Based upon this information, is there another way (outside of stored procedures in the db) to do what I want to do? I'm open to ideas. -
Dynamic Prepared statement--pls help
I need to create a prepared statement where i do not know how many parameters( or arguments i.e " ? ") will be passed. The arguments are decided dynamically while runtime...as in i may pass only a single argument or many.
example:
select * from employee_table where employee_id in (?,?....)
in the above query i may only one employee_id or may be more than one.This is decided during run time.I do not want to run a for loop for the number of employee is as this will cause performance issue. can anybody please tell me how these arguments can be generated dynamically
thanks 4 ur help in advanceWhen will you know the emp.Id ?
Reason is Once you get the emp.Id at runtime means you can assign this id to string variable using the comma separator and assigned this string to the query.
Example
String listOfEmpId = "e11,ee23,e55..."; and then use this variable in the query. -
Dynamically obtain parameter count for a prepared statement
Hi JDBC Gurus,
Given a prepared statement, is there a way to figure out the parameter count at runtime? I need this info. to prompt the user for parameter values at the right time from my GUI tool. Any help will be greatly appreciated.i don't know of any way to do this put perusing through the API i am wondering what the getMetaData method of PreparedStatement is supposed to do. it says returns the meta data of a ResultSet's columns but i think it could contain info about the parameters for the PreparedStatement. i guess i just don't see why that method is there... anyone?
-
ITunes Connect: Can't get out of "Prepare For Submission" state
My app is currently stuck in "Prepare For Submission" state.
I click "Submit For Review", then answer the 3 questions, then click "Submit".
Then it just spins for 5 minutes or so and reloads and I'm back where I started. "Prepare For Submission" again. I have already uploaded a binary and everything seems good to go.
The previous version of my app was rejected, so I updated the version number and am attempting to resubmit a new binary on top of it. Perhaps this is related to the issue? I tried this in Chrome as well as Safari with the same result.
Any help would be greatly appreciated.
Thanks!Update: I created a new build, bumped the version and tried again. This time it worked. Who knows...
-
Can any body Help me to prepare statement
I want to provide dynamic table name for preparestatement that i just pass table name every time and it pass me total number in that table.
I create this prepare statement
PreparedStatement prepStmt=conn_.prepareStatement("select count(*) Total from ?");
prepStmt.setString(1,"new");
but it is giving error
[JDBC SQL Server Driver] Line 1: Incorrect syntax near 'new'.
Any body can help me??
I will appreciate.In PreparedStatement, the setString method adds quotes at the start and at the end of your String.
So your request :
select count(*) Total from ?
is interpreted :
select count(*) Total from 'new'
One possible solution is to pass your tablename parameter directly in the precompiled request :
String myTableName = "new";
PreparedStatement prepStmt=conn_.prepareStatement("select count(*) Total from "+myTableName);
In your database, you will store as many precompiled Statement as you will call this method with different parameters.
Hope it helps ! -
Hello all!
I am trying to get this prepared statement to work but am getting an error that I cant understand.
Basically I have a class file that the ps resides in. I am calling the ps from a jsp.
Here is the code:
public void recordUsage(String userid, String ipaddress, String page, String filename)
String insertStatement = "INSERT INTO usageLog(userId,ipAddress, localTime, page, fileName) VALUES(?,?,?,?,?)";
try
{ java.util.Date currentDate=new java.util.Date();//Create a date object for the timestamp
java.sql.Timestamp ts=new java.sql.Timestamp(currentDate.getTime());//Create the timestamp from the above date object.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
objConn = java.sql.DriverManager.getConnection("jdbc:odbc:sensorWeek","","");
PreparedStatement ps = objConn.prepareStatement(insertStatement);
ps.setString(1, userid);
ps.setString(2, ipaddress);
ps.setTimestamp(3, ts);
ps.setString(4, page);
ps.setString(5, filename);
ps.executeUpdate();
objConn.commit();
ps.close();
objConn.close();
System.out.println("recordusage method called");
catch (SQLException s)
System.err.println("DataBase PROBLEM");
s.printStackTrace();
catch (Exception e)
System.err.println("Error in recordUsage method");
e.printStackTrace();
}Here is the error generated:(I hate to dump this on you)
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: sensorPac.methodClass.record(Ljava/lang/String;Ljava/lang/String;)V
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
at java.lang.Thread.run(Thread.java:534)
root cause
javax.servlet.ServletException: sensorPac.methodClass.record(Ljava/lang/String;Ljava/lang/String;)V
at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:536)
at org.apache.jsp.download_jsp._jspService(download_jsp.java:93)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:210)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.CertificatesValve.invoke(CertificatesValve.java:246)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2416)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:171)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:601)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:392)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:619)
at java.lang.Thread.run(Thread.java:534)
TIA!!And what makes you think that the above code is causing the problem?
Maybe you are looking for
-
Is the above message a real problem and what can I do about it?
-
Dear All, We are facing a problem on a particular date stock of some materials is showing in negative because issue qty is greater than receipt and stock qty. How it is possible that material is issued even if it is not in the stock. is it configura
-
Add custom fields in ML81n line item level
Hi All, We have a requirement to add custom field in ML81N. I have found an enhancement SRVDET and table CI_ESLLDB to add the custom field. But my problem is, I cant find the screen where can I add that custom field. Does anybody knows this? Apprecia
-
I mean exactly the same. Like down to the last detail!
-
Plugin customization from crm 4.0 to crm 2013
Hi, can anyone advice or help me to customize CRM 4.0 plugin code where using Product class, to CRM 2013. There is not product class (crm service) in CRM 2013 and I don't know how to customize below Code to CRm 2013 plugin here i attached snip of CRm