Toggle mysql concat sql query
I have a drop down menu on a form that lists GPs by their surname, surgery name and town:
$query_gp = "SELECT CONCAT(gp_surname, ' - ', gp_surgery, ', ', gp_town) as gplist, gp_id FROM gp ORDER BY gplist";
$gp = mysql_query($query_gp, $mypms) or die(mysql_error());
$row_gp = mysql_fetch_assoc($gp);
$totalRows_gp = mysql_num_rows($gp);
and then the php to put on the page and update a foreign key in a separate table:
<select name="gplist" class="main_text_field" id="gplist"style="width:150px;">
<?php
do {
?>
<option value="<?php echo $row_gp['gp_id']?>"<?php if (!(strcmp($row_gp['gp_id'], $row_demographics['FK_gp_id']))) {echo "SELECTED";} ?>><?php echo $row_gp['gplist']?></option>
<?php
} while ($row_gp = mysql_fetch_assoc($gp));
$rows = mysql_num_rows($gp);#
if($rows > 0) {
mysql_data_seek($gp, 0);
$row_gp = mysql_fetch_assoc($gp);
?>
</select>
Using a pair of radio buttons, I want to toggle the list order so that it is displayed in town order, I haven't got the foggiest about where to start - help please :-(
I am assuming what Bregent and Nancy mean is to allocate a value to the radio buttons then send that value to the page to process in what order you want the list to appear, either ORDER by gplist or gp_town
<form action="xxxxxxxxxx.php" method="post">
<input type="radio" name="gp" value="gpName">List by GP Name<br>
<input type="radio" name="gp" value="gpTown">List by Town
<input type="submit" value="Submit">
</form>
You would then use some php to get the value of 'gp' - the 'name' given to the radio button group (as above). The value of the radio button is assigned to a variable called $action and then re-assigned with the database column name you want the list to be ORDERED by.
<?php
$action = $_POST['gp'];
if ($action == "gpName") {
$action = "gplist";
elseif ($action == "gpTown") {
$action = "gp_town";
?>
Enclose the database query in a php if/else statement. IF the variable $action 'isset' then the list will be ordered by whatever radio button value is selected otherwise it will just be ordered by gplist:
if(isset($action)) {
$query_gp = "SELECT CONCAT(gp_surname, ' - ', gp_surgery, ', ', gp_town) as gplist, gp_id FROM gp ORDER BY '".$action."' ASC";
$gp = mysql_query($query_gp, $mypms) or die(mysql_error());
$row_gp = mysql_fetch_assoc($gp);
$totalRows_gp = mysql_num_rows($gp);
else {
$query_gp = "SELECT CONCAT(gp_surname, ' - ', gp_surgery, ', ', gp_town) as gplist, gp_id FROM gp ORDER BY gplist";
$gp = mysql_query($query_gp, $mypms) or die(mysql_error());
$row_gp = mysql_fetch_assoc($gp);
$totalRows_gp = mysql_num_rows($gp);
Similar Messages
-
JSTL, MySQL, Tomcat sql:query error
Hi to everyone...
This is my first post, but since im employed now as a java developer ill be here regulary.
Right now im trying to use the JSTL to make some simple sql selects in my JSPs....
Here�s the JSP code:
<%@ page language="java" import="java.lang.*,java.util.*" %>
<%@ taglib uri="/jstl-core" prefix="c" %>
<%@ taglib uri="/jstl-sql" prefix="sql" %>
<html>
<head>
<title> A first JSP database </title>
</head>
<body>
<sql:setDataSource scope="session" var="dataSource"
url="jdbc:mysql://127.0.0.1/zolltek" driver="com.mysql.jdbc.Driver"
user="root" password="root"/>
<!-- The following UPDATE works fine.. -->
<sql:update var="users" dataSource="${dataSource}" scope="session">
INSERT INTO test VALUES (7,'Paul Oakenfold')
</sql:update>
<!-- But the select screws up.... -->
<sql:query var="users" dataSource="${dataSource}" scope="session">
SELECT * FROM test WHERE 1
</sql:query>
</body>
</html>
...and the error message:
exception :
org.apache.jasper.JasperException:
SELECT * FROM test WHERE 1
: null
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:254)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
root cause
javax.servlet.ServletException:
SELECT * FROM test WHERE 1
: null
at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:531)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:84)
...and just for completion the importent part of my web.xml:
<taglib>
<taglib-uri>/jstl-core</taglib-uri>
<taglib-location>/WEB-INF/c-1_0.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/jstl-sql</taglib-uri>
<taglib-location>/WEB-INF/sql-1_0.tld</taglib-location>
</taglib>
i am using the jboss 3.2.3 tomcat bundle (tomcat 4.1.29)
and mysql 4.0.18 on W32 System....
the JSTL is installed and working - i can make <sql:update>Inserts without any problems, but any <sql:query>selects result in that error... so i guess the setDataSource is okay...
Any idea would be appreciated....
Thx
J�rgThose URIs you've got in your JSPs aren't correct. They should be:
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
These are the URIs defined in the standard.jar.
You'd be better off setting up a Tomcat JNDI data source for your application. That will externalize the connection parameters and make it unnecessary to refer to a data source in your JSPs.
You'd be even better off not putting SQL code in your JSPs. They're for presentation. Better to write a Java object that will communicate with the database on the JSP's behalf.
If you just want to select all the rows in the table, the query should be "SELECT * FROM test". You don't need a WHERE clause in that case.
If you change the URIs in your JSPs you should remove the <taglib> from your web.xml. It's not necessary. Tomcat will find the TLD by looking in the JARs in the CLASSPATH and matching the URIs. -
SQL Concat function seem not to work properly in SQL query data model. BIP 11g
I try to use this function to show entire name CONCAT(name, ' ', surname) and it doesnt show the surname. it looks like it only tooks 2 arguments. I use it with the option "Add element by expression" within a SQL Query - Data set.
Luciai don't believe you
please post more info, may be screen or sql or some more useful statement
CONCAT(name, ' ', surname) and it doesnt show the surname
may be because for some case "surname" is empty or may be you incorrect use concat function
one way mentioned by BluShadow is " || " operator - http://docs.oracle.com/cd/B28359_01/server.111/b28286/operators003.htm#SQLRF51156
and another is concat function http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions026.htm#SQLRF00619
so for your case it can be like
CONCAT(CONCAT(name, ' '), surname) -
Mysql equivalent oracle sql query is required
Hi all,
please help me convert mysql quyery into sql query.
select u.username, t.name as fullname, p.id as project_id, p.name as project,
(select count(a.resource_id) from pd_resource_task_alloc as a left OUTER JOIN pd_resource_task as b on a.task_id=b.task_id where a.task_id=t.id ) as allocatedTask,
(select count(a.resource_id) from pd_resource_task_alloc as a left OUTER JOIN pd_resource_task as b on a.task_id=b.task_id where a.task_id=t.id and b.task_status_id='2') as completedTask,
(select count(a.resource_id) from pd_resource_task_alloc as a left OUTER JOIN pd_resource_task as b on a.task_id=b.task_id where a.task_id=t.id and b.task_status_id!='2') as pendingTask,
c.name as category, sub.task_id, t.name, sub.bucket_date, sum(sub.alloc_time) as s
from (select rt.task_id, rt.resource_id, rt.project_id, rta.sequence, rta.alloc_time,DATE(th.creation_date) as creation_date,rt.start_date,th.task_status_id,rt.start_date as bucket_date from resource_task rt, resource_task_alloc rta ,task_history th
where rt.task_id = rta.task_id and rt.task_id = th.task_id and th.task_status_id >=2
and rt.resource_id = rta.resource_id and rt.project_id = rta.project_id
and rta.alloc_time > 0 and rt.start_date is not null ) as sub,
pd_tool_user u, pd_task t, pd_project p, pd_category c where sub.resource_id = u.id
and sub.start_date >='2011-11-01' and sub.creation_date <= '2011-11-31'
and sub.task_id = t.id and sub.project_id = p.id and
t.category_id = c.id
and sub.project_id='355'
group by p.project, u.username, p.id , u.name, sub.task_id, t.name, c.name,
sub.bucket_date order by u.username, sub.bucket_date, p.name, c.nameThanks,
P PrakashNot sure as we don't have any tables and data to work with, but firstly...
a) format your code to make it easier to see what's going on
b) don't mix ansi joins with regular joins
c) treat DATEs as DATEs
d) Table alias names don't use the "AS" keyword
First guess (obviously unteseted)...
select u.username
,t.name as fullname
,p.id as project_id
,p.name as project
,(select count(a.resource_id)
from pd_resource_task_alloc a
left OUTER JOIN pd_resource_task b on (a.task_id=b.task_id)
where a.task_id=t.id
) as allocatedTask
,(select count(a.resource_id)
from pd_resource_task_alloc a
left OUTER JOIN pd_resource_task b on (a.task_id=b.task_id)
where a.task_id=t.id
and b.task_status_id='2'
) as completedTask
,(select count(a.resource_id)
from pd_resource_task_alloc a
left OUTER JOIN pd_resource_task b on (a.task_id=b.task_id)
where a.task_id=t.id
and b.task_status_id!='2'
) as pendingTask
,c.name as category
,sub.task_id
,t.name
,sub.bucket_date
,sum(sub.alloc_time) as s
from (select rt.task_id
,rt.resource_id
,rt.project_id
,rta.sequence
,rta.alloc_time
,th.creation_date -- assuming creation_date is a DATE datatype?
,rt.start_date
,th.task_status_id
,rt.start_date as bucket_date
from resource_task rt
join resource_task_alloc rta on (rt.task_id = rta.task_id
and rt.resource_id = rta.resource_id
and rt.project_id = rta.project_id)
join task_history th on (rt.task_id = th.task_id)
where th.task_status_id >=2
and rta.alloc_time > 0
and rt.start_date is not null
) sub
join pd_tool_user u on (sub.resource_id = u.id)
join pd_task t on (sub.task_id = t.id)
join pd_project p on (sub.project_id = p.id)
join pd_category c on (t.category_id = c.id)
where sub.start_date >= to_date('2011-11-01','YYYY-MM-DD') -- assuming start_date is a DATE datatype
and sub.creation_date <= to_date('2011-11-31','YYYY-MM-DD') -- assuming creation_date is a DATE datatype
and sub.project_id='355'
group by p.project
,u.username
,p.id
,u.name
,sub.task_id
,t.name
,c.name
,sub.bucket_date
order by u.username
,sub.bucket_date
,p.name
,c.name -
How to determine a sql query size to display a progress bar
I would like to show a progress of an sql query within a jsp page.
Background:
I have a reporting web application, where over 500 contacts can run reports based on different criteria such as date range....
I current display a message stating 'executng query please wait', however the users (hate users) do not seem to wait, thereofore they decide to run the query all over again which affected my reportign sever query size (eventually this crashes, stopping all reports)
Problem:
The progress bar is not a problem, how would I determine the size of the query at runtime therefore adding the time onto my progress bar.Yes it's doable (we do it) but it sure ain't easy.
We've got about 23,500,000 features (and counting) in a geodata database. Precise spatial selection algorithms are expensive. Really expensive.
We cannot impose arbitrary limits on search criteria. If the client requires the whole database we are contractually obligated to provide it...
For online searches We use statistics to approximate the number of features which a given query is likely to return... more or less the same way that the query optimiser behind any half decent (not mysql (5 alteast)) database management system does.
We have a batch job which records how many features are linked to each distinct value of each search criteria... we just do the calculations (presuming a normal (flat) distribution) and...
... if the answer is more than a 100,000 we inform the user that the request must be "batched", and give them a form to fill out confirming there contact details. We run the extract overnight and send the user an email containing a link which allows them to download the result the next morning.
... if the answer is more than a million features we inform the user that the request must batched over the weekend... same deal as above, except we do it over the weekend to (a) discourage this; and (b) the official version ensure we have enough time to run the extract without impinging upon the maintenance window.
... if the answer is more than 5 million we display our brilliant "subscribe to our DVD service to get the latest version of the whole shebang every three months (or so), so you can kill your own blooody server with these ridiculous searches" form.
Edited by: corlettk on Dec 5, 2007 11:12 AM -
SQL query with Java Server Pages
Hey,
I'm trying to read some information from database with SQL Query. How I can put the parameter that I get from previous *.jsp page to SQL query?
Technologies that I use are WML, JSP and MySQL.
I can get the parameter by method getParameter() and it is correct.
But how to but the requested parameter into sql query and complete the sql query?
Should I read it to some variable before putting it to sql query?
*/ this works fine */
out.println("<p>periodi"+request.getParameter("periodi"+"loppu</p>");
/* this doesn't work */
ResultSet tulokset = lause.executeQuery("select * from kurssi where periodi='+request.getParameter("periodi")+'");
/* this doesn't work */
String periodi=request.getParameter("periodi");
ResultSet tulokset = lause.executeQuery("select * from kurssi where periodi='periodi' '");
Thanks,
RampeHey,
I'm trying to read some information from database
se with SQL Query. How I can put the parameter that I
get from previous *.jsp page to SQL query?
Technologies that I use are WML, JSP and MySQL.
I can get the parameter by method getParameter()
() and it is correct.
But how to but the requested parameter into sql
ql query and complete the sql query?
Should I read it to some variable before putting it
it to sql query?
*/ this works fine */
out.println("<p>periodi"+request.getParameter("periodi"
"loppu</p>");
/* this doesn't work */
ResultSet tulokset = lause.executeQuery("select * from
kurssi where
periodi='+request.getParameter("periodi")+'");
/* this doesn't work */
String periodi=request.getParameter("periodi");
ResultSet tulokset = lause.executeQuery("select *
* from kurssi where periodi='periodi' '");
Thanks,
RampeTry this
ResultSet tulokset = lause.executeQuery("select * from kurssi where periodi=" + "'" +request.getParameter("periodi")+"' " );this should work -
SQL query with parameter returns empty result set, please help !!!
Hi there,
When I use the following query :
<sql:query var="beroepsthemas" >
select *
from beroepsthemas
where beroepsthemaid = ?
<sql:param value="12"/>
</sql:query>
When I want to browse the result set with :
<c:forEach items="${beroepsthemas.rows}" var="rij">
it shows no records. But it must return at least one.
All my jsp pages with sql queries and parameters have the same problem.
This is all on my test environment. I'm using Ubuntu 5.10, Netbeans5.0, JDK 1.5_06, application runs in Bundeled Tomcat 5.5.9, MySQL 4.1.12, mysql-connector3.1.6
When the same code is run on the live environment, it works just fine.
The difference is :
Mysql 4.1.10a, tomcat5.5.9, mysql-connector3.1.6
What can there be wrong !!When the same code is run on the live environment, it
works just fine.
The difference is :
Mysql 4.1.10a, tomcat5.5.9, mysql-connector3.1.6
I didn't catch this. I think you may need to update the database driver. -
Is there a way to consolidate calculations used in SQL Query Data Sets?
I am building SQL Query Data Sets against multiple DB Views which all have different date formats. I have the date parameter working well, but want to consolidate the changes that I have to do to it especially for the quarter. For example the SQL against a monthly view would use "where year_month > to_char(:ST_DATE, 'YYYY-MM')" which is not too hard, but to make that work for the quarterly view I need several concats and a decode to get a "> '2012-Q2'". I would like not to have to do this within every where clause. I had put this into a global element hoping to use that in a filter for the data set, but the filter does not have access to global elements only parameters.
Is there any way to refer to a calculated global element from the data set to do this? I am using Layout Templates, so even if I wanted to I could not do the condition within the template.
Thanks,
RickChange the following line to include the red coloured parts
<div class="MasterColumn" spry:repeat="ds4" spry:setrow="ds4" spry:hover="MasterColumnHover" spry:select="MasterColumnSelected">
<span>{Dsp_#}</span><span>{Dsp_WkDay}</span><span>{Dsp_Event}</span>
</div>
The add the following style rule to your document:
.MasterColumn span {
display: inline-block;
I hope this helps.
Ben -
Passing a string into an SQL query IN statement
Hello,
I need to connect to a database to pull some data to dynamically create a form based on the data I pull back. My SQL query works fine when I manually run it through a SQL client tool, but when I try to pass it through my workflow I'm having trouble with passing my string into the IN part of the statement. So if for example my SQL query is:
SELECT Field1, Field2, Field3 FROM Table1 WHERE Field4 IN (?)
I have a process variable that has the string I'm trying to pass into the ?, but I don't seem to be able to get the query to run. I have tried setting up my query to run as a Parameterized Query (passing my string process variable into the ?), and by setting the query up through xPath (where I am calling my process variable with an xPath declaration), but am not having any luck.
The process variable I am trying to pass is formatted such that I'm passing 'Value1','Value2','Value3' but I can reformat this string if need be. Even with using test data I can't get the query to return anything. For test data I have tried: 'Value1','Value2','Value3' ; Value1','Value2','Value3 ; Value1,Value2,Value3 but the query never returns any data. I can't seem to see how to format the string to pass into the query. The Query will work with a single Value in the test data, but as soon as I try to pass multiple values within the string it fails. Any suggestions?The problem looks to be a limit on what I can pass into the SQL query component. My string is coming from data returned from another database. I take the xml output from that database call, pass it through a set variable component to remove my xml tags from the string, and then format the string in a script component (I have to do it this way because of the way the data coming out of my first database call). I've put in loggers, and can see that the string I'm passing into my query that is giving me problems, is formatted the same way as if I were to use the concat function Scott listed above. It looks like there is a limitation on what can be passed in my variable. I have tried creating my entire SQL query statement in a set variable component, and then just calling the process variable that holds that statement, but there is a character limit of 128 character for what can be passed in a variable through xpath in the SQL query component.
The next thing I tried was changing my SQL where clause. Instead of passing my variable directly into the IN statement I set up a PATINDEX('%:'+countyname+ ':%', ?) > 0 call to check for the values in my database call. As you can see I took out the "," that I was passing as part of my string, thinking that the SQL component was getting confused by them, and placed ":" characters around my values being passed in my string variable. No matter what I try to do though I'm not able to get the query to run. The component looks like it is taking my string, and is seeing the whole thing as a string instead of passing it as individual values within a string.
I think I'm getting close, but I keep getting a Content not allowed in prolog exception in the server logs. -
When I put my sql query in a resultset it breaks my code. Not getting any specific errors, but it exits the try and stops performing. The problem is when I try to put a resultset into a variable. Here is my code:
class Reader1 {
public Reader1(String command){
System.out.println("reader 1 has been called");
try {
int c;
int m;
Statement stmt;
System.out.println("reader 1 before sql");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/jdbase?user=root&password=bond007?");
String query = "SELECT current_connections, max_connections FROM master WHERE compid ='mjtrends'";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("reader 1 after sql");
c = rs.getInt("current_connections");
m = rs.getInt("max_connections");
stmt.close();
conn.close();
System.out.println("got sql values"); }//end try
catch (Exception ex) {
}1) You may want to edit the code you post to a public forum so it doesn't contain the root password to your database.
2) This:
catch(Exception e) {
}is called "swallowing" the exception. It is bad. You get no information from this. It will be easier to debug the problem if you do this:
catch (Exception e) {
e.printStackTrace();
}Good luck. -
Hi Experts,
Can any one tell me how to use SQL Query in WebDynpro Java to access the Database? Please mention the code where to use and the configuration to be done.
Thanks in Advance
NaveenHi,
Following is the code for max db change this driver to SQL server/Oracle
Connection conn = null;
try {
//sapdbc.jar is the MySQL Driver it should be part ot the java/lib or ext
Class.forName("com.sap.dbtech.jdbc.DriverSapDB");
String urlConn = "jdbc:sapdb://localhost/maxdb1"; //replace localhost and the maxdb1 with your server name and database.
String username = "userID";
String password = "password";
conn = DriverManager.getConnection(urlConn, username, password);
System.out.println("connected to DB...");
//Here the table name is table one which contains 1 field of data type string, change the following as per yours.
PreparedStatement stmt = conn.prepareStatement("insert into table1 values(?)");
//get the value entered in the inputfield which is mapped to an attribute called ID, change ths according to your req.
String value = wdContext.currentContextElement().getID();
conn.setAutoCommit(false);
stmt.setString(1, value);
stmt.execute();
conn.commit();
} catch (Exception e) {
e.printStackTrace();
} // catch
Regards
Ayyapparaj -
hi all,
i created a report that displays results based on this query initially.
select *
from EMP
where 1=1;
i'm using a SQL Query (PL/SQL Function Body Returning SQL Query).
i have search items in my page like empno, lastname, firstname, middle, email_address etc... when i place a value for lastname then in my query it should add AND LASTNAME = :P1_LASTNAME.
so the query returned should now have
select *
from EMP
where 1=1
and LASTNAME = :P1_LASTNAME;
is this possible?
i was thinking something like looping for all search items in the page (ie. text, popup lov, datetimepicker) then check whether the item is null or not... when not null then probably get the substring of the item name like (ie. substr(:P1_LASTNAME) and get only LASTNAME then add "=" then concat it with the item name. not sure if this is possible though.
thanks
allenhi denes,
thanks for the sample... i noticed that the sample hard codes additional conditions to be added to the sql query which is okay when the search criteria is less than 5-10... but i'm thinking if the search criteria will be like 15-30 fields or make all fields searchable, this might be uncomfortable.
what i was thinking is like loop thru all the items i.e.
declare
sql varchar2(4000) := 'select * from emp where 1=1';
begin
for i in (select * from all_items_in_apex) -- this is just an example.
loop
if i.value is not null then
sql := sql || ' and ' || i.column || '=' || i.value;
end if;
end loop;
end;
the only thing is that i don't know if there's a possible replacement for the clause (select * from all_items_in_apex).
sorry if i'm asking too much but this is how i normally do it in forms. the suggestion in the link you provided should be sufficient but i was just wondering if this idea is also possible.
thanks again.
allen -
Hello everyone! I have a small problem with binding a DataSource object via JNDI and retrieving it in a web application. This is the case:
I did not wish to make the DataSource available through the server.xml, because I want to create applications that can be bundled in a simple .war file. So I create the DataSource when the context is created in the contextInitialized() method of ServletContextListener like this:
InitialContext initialContext = new InitialContext();
Properties properties = new Properties();
properties.setProperty( "driverClassName", "com.mysql.jdbc.Driver" );
properties.setProperty( "factory", "org.apache.commons.dbcp.BasicDataSourceFactory" );
properties.setProperty( "username", servletContext.getInitParameter( "dbUser" ) );
properties.setProperty( "password", servletContext.getInitParameter( "dbPass" ) );
properties.setProperty( "url", servletContext.getInitParameter( "dbUrl" ) );
properties.setProperty( "defaultAutoCommit", "false" );
properties.setProperty( "maxActive", "25" );
properties.setProperty( "initialSize", "15" );
properties.setProperty( "maxIdle", "10" );
properties.setProperty( "testOnBorrow", "true" );
properties.setProperty( "testOnReturn", "true" );
properties.setProperty( "testWhileIdle", "true" );
properties.setProperty( "validationQuery", "SELECT 1" );
properties.setProperty( "removeAbandoned", "true" );
DataSource dataSource = BasicDataSourceFactory.createDataSource( properties );
initialContext.rebind( "daers", dataSource );Please comment if you think this is a bad idea!
All the above seems to work fine. When I try to retrieve the DataSource in a .jsp file then it all works fine like this:
<% try {
javax.naming.InitialContext initialContext = new javax.naming.InitialContext();
java.sql.Connection conn = ( ( javax.sql.DataSource )initialContext.lookup( "daers" )).getConnection();
java.sql.Statement statement = conn.createStatement();
java.sql.ResultSet resultSet = statement.executeQuery("SELECT users.name FROM users;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
} catch ( java.sql.SQLException e ) {
e.printStackTrace();
} catch ( javax.naming.NamingException e ) {
e.printStackTrace();
%>But when I try to execute the same sql query through the appropriate JSTL taglib I get a:
javax.servlet.ServletException: Unable to get connection, DataSource invalid: "java.sql.SQLException: No suitable driver"The JSTL code I use is this:
<sql:query dataSource = "daers" var = "query" scope = "page">
SELECT users.name
FROM users
</sql:query>I do put both of the two above pieces of code in the same .jsp page and the first works but the second causes the exception...
Any clues..?
Is it illegal to lookup a DataSource in <sql: dataSource=...> if the DataSource is not registered in the server.xml file..?
If so, do I have any alternatives (like putting the DataSource as a servlet context variable)..?I added a response in your original message:
http://forum.java.sun.com/thread.jspa?messageID=9629812
Let's keep to it since splitting things across two posts might be confusing. -
Problems witth sql query from servlet
hi,
I have a servlet that accesses a MySql database to get the ID of an employee based on employee name (grabbed from session). My problem is that :
empName contains a whitespace (String empName ="abc xyz")
When I try to give this to the query:
String query ="select id from user where eName =" +empName;
Now I keep getting a "SQL syntax error:please check your syntax to use near 'xyz' at line 1." here which I think is because of the white space in the empName. ( I tried dummy empName without spaces).
How do I get around this ..I cannot keep the names in the database without any space since they are being dislpayed in other pages. I tried doing a trim() on the empName before passing it to the sql query but I keep getting the same error.
Is there any way I could query the DB with a white space in the empName?
Thanks,
G.
Is there any way toSecond of all: Use prepared statements:
like:
insertStatement = "SELECT ? FROM ? WHERE name=?";
stmnt = _sql_connection.prepareStatement(insertStatement);
stmnt.setString(1, "name");
stmnt.setString(2, "table");
stmnt.setString(3, "test");This is more secure. If you do it the above way i could enter some thing like
*; DROP TABLE *; --
You dont want a user to kill your whole db, dont you?
so your querry String query ="select id from user where eName = '" +empName +"'"; will end up:
select id from user where eName = '*'; DROP TABLE *; -- 'where everything after -- is ignored because this is a comment flag. -
I want to execute SQL query in the JavaBean.
Is there any problem in the following code.
There is no error message, but the database do not update. And I try to use JSP , it is ok. What is the problem in JavaBean ??
How to execute SQL in JavaBean ???
Please help ! Thank you !
test.jsp - call UserTrace.java
UserTrace.java - execute SQL
Code:
** test.jsp **
<%@ page language="java" contentType="text/html" %>
<%@ page import="user.*, java.util.*" %>
<jsp:useBean id="usertrace" class="user.UserTrace" scope="session" />
<%
if (session.isNew())
session.setAttribute("usertrace", usertrace);
session.setMaxInactiveInterval(15);
%>
** UserTrace.java **
package user;
import java.util.*;
import javax.servlet.http.*;
import java.io.*;
import java.beans.*;
import java.sql.*;
import user.*;
public class UserTrace implements javax.servlet.http.HttpSessionBindingListener {
private Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String sql;
public void valueBound(HttpSessionBindingEvent event) {
public void valueUnbound(HttpSessionBindingEvent event) {
try {
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=abc&password=abcd");
stmt = con.createStatement();
sql = "insert into list(username, session_id) values ('mary', 'xxxxxxxxx')";
int count = stmt.executeUpdate(sql);
catch (ClassNotFoundException e) {
catch (SQLException e) {
}Hi,
U can use the following code:
/********** IMPORTING PACKAGES AND CLASSES *******/
// General package id
package id;
//Import the Vector class as this bean handles Vector.
import java.util.Vector;
//Import the SQL class to create the connections,statement,resultset etc.,
import java.sql.*;
//Import the SQL Types to call the setNull Method.
import java.sql.Types.*;
/* Main Class */
public class dataBean
/*********** Global Declarations ********/
// To create the connection object
Connection con;
// To create the Statement object
Statement stmt;
// To create the PreparedStatement object
PreparedStatement psmt;
// To Handle the ResultSet
ResultSet rs;
// Most of the method need to hold the querystring for which qryString variable declare globally.
String qryString=null;
/************ METHODS **************/
/* To set the connection object
con - Connection object
public void setConnection(Connection con)
try
this.con = con;
catch(Exception e)
/* insertRecord with column type argument
tblNameString - Name of the Table
dataVector - vector contains the values according to the table order
eg., element(0) has first field, element(1) has second field vice versa
colType - String array contains type of all the fields.
return true - if record inserted successfully
fase - if insertion fails
public boolean insertRecord(String tblNameString,Vector dataVector,String colType[])
boolean sucFlag=false;
try
String commaString = "";
int fieldCount = dataVector.size();
for (int i=0;i<fieldCount-1;i++)
commaString +="?,";
commaString+="?";
if (fieldCount > 0)
qryString = "insert into "+tblNameString+" values ("+commaString+")";
psmt = con.prepareStatement(qryString);
for(int i=0;i<colType.length;i++)
if (colType.equals("I"))
psmt.setInt(i+1,Integer.parseInt(dataVector.elementAt(i).toString()));
else if (colType[i].equals("F"))
psmt.setFloat(i+1,Float.parseFloat(dataVector.elementAt(i).toString()));
else if (colType[i].equals("S") || colType[i].equals("D"))
psmt.setString(i+1,dataVector.elementAt(i).toString());
else if (colType[i].equals("IN")||colType[i].equals("FN"))
psmt.setNull(i+1,java.sql.Types.NUMERIC);
else if (colType[i].equals("SN"))
psmt.setNull(i+1,java.sql.Types.VARCHAR);
else if (colType[i].equals("DN"))
psmt.setNull(i+1,java.sql.Types.DATE);
int sucCnt = psmt.executeUpdate();
if (sucCnt > 0) sucFlag=true;
catch(Exception e)
return sucFlag;
/* insertRecord without column type argument
tblNameString - Name of the Table
dataVector - vector contains the values according to the table order
eg., element(0) has first field, element(1) has second field vice versa
return true - if record inserted successfully
fase - if insertion fails
public boolean insertRecord(String tblNameString,Vector dataVector)
boolean sucFlag=false;
Vector colType = getColumnType(tblNameString);
try
String commaString = "";
int fieldCount = dataVector.size();
for (int i=0;i<fieldCount-1;i++)
commaString +="?,";
commaString+="?";
if (fieldCount > 0)
qryString = "insert into "+tblNameString+" values ("+commaString+")";
psmt = con.prepareStatement(qryString);
for(int i=0;i<colType.size();i++)
if (colType.elementAt(i).toString().equals("I"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.NUMERIC);
else
psmt.setLong(i+1,Long.parseLong(dataVector.elementAt(i).toString()));
else if (colType.elementAt(i).toString().equals("F"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.NUMERIC);
else
psmt.setDouble(i+1,Double.parseDouble(dataVector.elementAt(i).toString()));
else if (colType.elementAt(i).toString().equals("S"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.VARCHAR);
else
psmt.setString(i+1,dataVector.elementAt(i).toString());
else if (colType.elementAt(i).toString().equals("D"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.DATE);
else
psmt.setString(i+1,dataVector.elementAt(i).toString());
int sucCnt = psmt.executeUpdate();
if (sucCnt > 0) sucFlag=true;
catch(Exception e)
return sucFlag;
/* insert particular fields
tblNameString - Name of the Table
dataVector - vector which contains the values according to the table order
eg., element(0) has first field, element(1) has second field vice versa
colType - String array contains type of all the fields.
return true - if record inserted successfully
fase - if insertion fails
public boolean insertRecordPart(String tblNameString,Vector dataVector,String colType[])
boolean sucFlag=false;
String fieldString=" ";
try
String commaString = "";
int fieldCount = dataVector.size();
for (int i=0;i<(fieldCount/2)-1;i++)
commaString +="?,";
commaString+="?";
if (fieldCount > 0)
String valueString[]= new String[fieldCount];
for (int i=0,j=0;i<fieldCount;i+=2,j++)
fieldString=fieldString+dataVector.elementAt(i)+",";
valueString[j]=dataVector.elementAt(i+1).toString();
if (fieldString.substring(fieldString.length()-1,fieldString.length()).equals(","))
fieldString=fieldString.substring(0,fieldString.length()-1);
qryString = "insert into "+tblNameString+"("+fieldString+") values ("+commaString+")";
psmt = con.prepareStatement(qryString);
for (int i=1,j=0;i<fieldCount;i+=2,j++)
if (colType[j].equals("I"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(j+1,java.sql.Types.NUMERIC);
else
psmt.setInt(j+1,Integer.parseInt(dataVector.elementAt(i).toString()));
else if (colType[j].equals("L"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(j+1,java.sql.Types.NUMERIC);
else
psmt.setLong(j+1,Long.parseLong(dataVector.elementAt(i).toString()));
else if (colType[j].equals("F"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(j+1,java.sql.Types.NUMERIC);
else
psmt.setFloat(j+1,Float.parseFloat(dataVector.elementAt(i).toString()));
else if (colType[j].equals("DB"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(j+1,java.sql.Types.NUMERIC);
else
psmt.setDouble(j+1,Double.parseDouble(dataVector.elementAt(i).toString()));
else if (colType[j].equals("S"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(j+1,java.sql.Types.VARCHAR);
else
psmt.setString(j+1,dataVector.elementAt(i).toString());
else if (colType[j].equals("D"))
if (dataVector.elementAt(i)==null||dataVector.elementAt(i).toString().equals(""))
psmt.setNull(j+1,java.sql.Types.DATE);
else
psmt.setString(j+1,dataVector.elementAt(i).toString());
int sucCnt = psmt.executeUpdate();
if (sucCnt > 0) sucFlag=true;
catch(Exception e)
return sucFlag;
/* Get Column Type of require table fields
tblNameString - Name of the table
return vector which contains the column types of the desired table
public Vector getColumnType(String tblNameString)
int colCount = 0;
String locString="";
Vector colVector = new Vector();
try
qryString = "select DATA_TYPE from user_tab_columns where table_name=? ORDER BY COLUMN_ID";
psmt = con.prepareStatement(qryString);
psmt.setString(1,tblNameString.toUpperCase());
rs = psmt.executeQuery();
while (rs.next())
colCount = rs.getMetaData().getColumnCount();
for(int i=1;i<=colCount;i++)
locString = rs.getString(i);
colVector.addElement(locString.equals("DATE")?"D":locString.equals("NUMBER")?"F":locString.equals("VARCHAR2")?"S":locString.equals("VARCHAR")?"S":"");
rs.close();
catch(Exception e)
return colVector;
/* update record
tblNameString - Name of the Table
dataVector - vector which contains the values according to the table order
eg., element(0) has first field, element(1) has second field vice versa
colType - String array contains type of all the fields.
return true - if record successfully updated
false - if Update fails
public boolean updateRecord(String tblNameString,Vector dataVector,String colType[],String whereString)
boolean sucFlag=false;
String fieldString=" ";
try
String commaString = "";
int fieldCount = dataVector.size();
for (int i=0;i<fieldCount-1;i++)
commaString +="?,";
commaString+="?";
if (fieldCount > 0)
String valueString[]= new String[fieldCount];
for (int i=0,j=0;i<fieldCount;i+=2,j++)
fieldString=fieldString+dataVector.elementAt(i)+"=?,";
valueString[j]=dataVector.elementAt(i+1).toString();
if (fieldString.substring(fieldString.length()-1,fieldString.length()).equals(","))
fieldString=fieldString.substring(0,fieldString.length()-1);
qryString = "update "+tblNameString+" set "+fieldString+" "+whereString;
psmt = con.prepareStatement(qryString);
for(int i=0,vectorPos=1;i<colType.length;i++,vectorPos+=2)
if (colType[i].equals("I"))
if (dataVector.elementAt(vectorPos)==null||dataVector.elementAt(vectorPos).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.NUMERIC);
else
psmt.setInt(i+1,Integer.parseInt(dataVector.elementAt(vectorPos).toString()));
else if (colType[i].equals("L"))
if (dataVector.elementAt(vectorPos)==null||dataVector.elementAt(vectorPos).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.NUMERIC);
else
psmt.setLong(i+1,Long.parseLong(dataVector.elementAt(vectorPos).toString()));
else if (colType[i].equals("F"))
if (dataVector.elementAt(vectorPos)==null||dataVector.elementAt(vectorPos).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.NUMERIC);
else
psmt.setFloat(i+1,Float.parseFloat(dataVector.elementAt(vectorPos).toString()));
else if (colType[i].equals("DB"))
if (dataVector.elementAt(vectorPos)==null||dataVector.elementAt(vectorPos).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.NUMERIC);
else
psmt.setDouble(i+1,Double.parseDouble(dataVector.elementAt(vectorPos).toString()));
else if (colType[i].equals("S"))
if (dataVector.elementAt(vectorPos)==null||dataVector.elementAt(vectorPos).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.VARCHAR);
else
psmt.setString(i+1,dataVector.elementAt(vectorPos).toString());
else if (colType[i].equals("D"))
if (dataVector.elementAt(vectorPos)==null||dataVector.elementAt(vectorPos).toString().equals(""))
psmt.setNull(i+1,java.sql.Types.DATE);
else
psmt.setString(i+1,dataVector.elementAt(vectorPos).toString());
int sucCnt = psmt.executeUpdate();
if (sucCnt > 0) sucFlag=true;
} // end of if
} // end of try
catch(Exception e)
return false;
return sucFlag;
public ResultSet getResultSet(String selectString)
try
stmt = con.createStatement();
rs = stmt.executeQuery(selectString);
catch(Exception e)
System.out.println(e.getMessage());
finally
return rs;
/* Get Query Result
selectString - Query
return the result vector based on the querystring
public Vector getResultVector(String selectString)
Vector resVector = new Vector();
try
stmt = con.createStatement();
rs = stmt.executeQuery(selectString);
while (rs.next())
resVector.addElement(rs.getString(1));
resVector.addElement(rs.getString(2));
catch(Exception e)
System.out.println(e.getMessage());
finally
return resVector;
/* return next consecutive number
tablenName - Name of the table for which the number to be generated
serialFiel - Name of the field for which the number to be generated
whereString - where condition to filter the records if composite key found,
it can be empty if there is no composite primary key.
startNumber - if there is no record exists in the table, set the starting number
public String getCurrentSerial(String tableName,String serialField,String whereString,String startNumber)
String queryString = "select max(to_number("+serialField+")) from "+tableName+" "+whereString;
int maxSerial=0;
try
psmt = con.prepareStatement(queryString);
rs = psmt.executeQuery();
while (rs.next())
maxSerial = rs.getInt(1);
if (maxSerial < 0)
maxSerial=Integer.parseInt(startNumber);
else
maxSerial+=1;
rs.close();
catch(Exception e)
return String.valueOf(maxSerial);
/* return next consecutive number
tablenName - Name of the table for which the number to be generated
serialFiel - Name of the field for which the number to be generated
whereString - where condition to filter the records if composite key found,
it can be empty if there is no composite primary key.
Note : if there is no record exists in the table, it starts with 1
public String getCurrentSerial(String tableName,String serialField,String whereString)
String queryString = "select max(to_number("+serialField+")) from "+tableName+" "+whereString;
int maxSerial=0;
try
stmt = con.createStatement();
rs = stmt.executeQuery(queryString);
while (rs.next())
maxSerial = rs.getInt(1);
if (maxSerial < 0)
maxSerial=1;
else
maxSerial+=1;
rs.close();
catch(Exception e)
System.out.println("Error from max serialX:"+e.getMessage());
return String.valueOf(maxSerial);
/* return the currnent user name */
public String getCurrentUser()
Statement stmt=null;
ResultSet rs=null;
String queryString = "select user from dual";
String userName = "";
try
stmt = con.createStatement();
rs = stmt.executeQuery(queryString);
while (rs.next())
userName = rs.getString(1);
rs.close();
catch(Exception e)
return userName;
/* return current user along with server's current date
example : userName#today
public String getCurrentUserDate()
Statement stmt=null;
ResultSet rs=null;
String queryString = "select user,to_char(sysdate,'dd-mon-yyyy') from dual";
String userName = "";
String todayDate= "";
try
stmt = con.createStatement();
rs = stmt.executeQuery(queryString);
while (rs.next())
userName = rs.getString(1);
todayDate = rs.getString(2);
rs.close();
catch(Exception e)
return userName+"#"+todayDate;
/* return server's current date */
public String getCurrentDate()
Statement stmt=null;
ResultSet rs=null;
String queryString = "select to_char(sysdate,'dd-mon-yyyy') from dual";
String todayDate= "";
try
stmt = con.createStatement();
rs = stmt.executeQuery(queryString);
while (rs.next())
todayDate = rs.getString(1);
rs.close();
catch(Exception e)
return todayDate;
/* return true if atleast one record found in the table
tblName : Name of the table
whereString : Where condition to filter the records
public boolean isRecordExists(String tblName,String whereString)
String queryString = "select count(1) from "+tblName+" "+whereString;
boolean recFound = false;
try
stmt = con.createStatement();
rs = stmt.executeQuery(queryString);
while (rs.next())
if (rs.getInt(1)==0)
recFound = false;
else
recFound = true;
rs.close();
catch(Exception e)
return recFound;
// round off decimal Places
public String fixDecimal(String sourceString,int digits)
String tmpText="",decimalPart="",returnText="";
try
sourceString = String.valueOf(Double.parseDouble(sourceString));
tmpText = sourceString.substring(sourceString.indexOf(".")+1);
if (tmpText.length() > digits)
decimalPart = tmpText.substring(0,digits);
if (Integer.parseInt(tmpText.substring(digits,digits+1))>=5)
decimalPart = String.valueOf(Integer.parseInt(decimalPart)+1);
tmpText = decimalPart;
if (decimalPart.length() > 3) // to check wheter 1000 reached, if yes add 1 to actual text
returnText = String.valueOf(Integer.parseInt(sourceString.substring(0,sourceString.indexOf(".")))+1);
else
returnText = sourceString.substring(0,sourceString.indexOf("."))+"."+tmpText;
else // if user entered decimal is with in 3 digits
if (tmpText.equals("0"))
returnText = sourceString.substring(0,sourceString.indexOf("."));
else
returnText = sourceString.substring(0,sourceString.indexOf("."))+"."+tmpText;
catch(Exception e)
System.out.println(e.getMessage());
return sourceString;
System.out.println(returnText);
return returnText;
} // end of main class
Access this Bean in JSP as follows:
<%@ page language="java" %>
<%@ page import="java.util.*"%>
<%@ include file="../connectionSetup.jsp"%>
<jsp:useBean id="dataBeanObj" class="id.dataBean"/>
<html>
<head>
<title>ADDRESS MASTER FORM</title>
<style type="text/css">
.tData
font-family : sans-serif;
font-size : 9px;
font-weight : bolder;
color : navy;
.buttonStyle
font-family : sans-serif;
font-size :10px;
</style>
</head>
<%
dataBeanObj.setConnection(con);
String curCode="";
String consFld = request.getParameter("consfld")==null?"":request.getParameter("consfld");
String cat = request.getParameter("cat")==null?"a":request.getParameter("cat").equals("a")?"a":"u";
boolean updateFlag=false,isWrongCountry=false;
String code="";
String name="";
String add1="";
String add2="";
String add3="";
String state="";
String country="";
String zip="";
String am_pcouncode="";
String am_pareacode="";
String am_psubcode="";
String am_fcouncode="";
String am_fareacode="";
String am_fsubcode="";
String am_phone="";
String am_fax="";
String email="";
String notes="";
String telex="";
String mobile="";
String popup="";
code = request.getParameter("code")==null?"":request.getParameter("code");
name = request.getParameter("name")==null?"":request.getParameter("name");
popup = request.getParameter("popup")==null?"":request.getParameter("popup");
String submitMode = request.getParameter("submit_mode")==null?"":request.getParameter("submit_mode");
String editMode = request.getParameter("edit_hidden")==null?"null":request.getParameter("edit_hidden");
if (name != null && !submitMode.equals("yes")) // ready to retrieve records
if (!code.equals(""))
rs = dataBeanObj.getResultSet("select am_code code,am_name name,am_address_1 add1,am_address_2 add2,am_address_3 add3,am_country country,am_state state,am_zip zip,am_phone phone,am_fax fax,am_e_mail email,am_notes notes,am_telex telex,am_mobile mobile from id_vms_address_master where am_code='"+code+"'");
else
rs = dataBeanObj.getResultSet("select am_code code,am_name name,am_address_1 add1,am_address_2 add2,am_address_3 add3,am_country country,am_state state,am_zip zip,am_phone phone,am_fax fax,am_e_mail email,am_notes notes,am_telex telex,am_mobile mobile from id_vms_address_master where upper(am_name)='"+name.toUpperCase()+"'");
if (rs.next()) // if record found
code = rs.getString("code"); // retrieve code
name = rs.getString("name"); // retrieve name
add1 = rs.getString("add1"); // retrieve address 1
add2 = rs.getString("add2"); // retrieve address 2
add3 = rs.getString("add3"); // retrieve address 3
country = rs.getString("country"); // retrieve country
state = rs.getString("state"); // retrieve state
zip = rs.getString("zip"); // retrieve zip
am_phone = rs.getString("phone"); // retrieve phone
am_fax = rs.getString("fax"); // retrieve fax
email = rs.getString("email"); // retrieve email
notes = rs.getString("notes"); // retrieve notes
telex = rs.getString("telex"); // retrieve telex number
mobile = rs.getString("mobile"); // retrieve mobile number
else if (submitMode.equals("yes")) // ready to submit
code = request.getParameter("code"); // get the input code
name = request.getParameter("name"); // get the input name
add1 = request.getParameter("address1"); // get the input address 1
add2 = request.getParameter("address2"); // get the input address 2
add3 = request.getParameter("address3"); // get the input address 3
country = request.getParameter("country"); // get the input country
state = request.getParameter("state"); // get the input state
zip = request.getParameter("zip"); // get the input zip
am_pcouncode = request.getParameter("pcouncode"); // get the input phone country code
am_pareacode = request.getParameter("pareacode"); // get the input phone area code
am_psubcode = request.getParameter("psubscode"); // get the input phone subscriber code
am_fcouncode = request.getParameter("fcouncode"); // get the input fax country code
am_fareacode = request.getParameter("fareacode"); // get the input fax area code
am_fsubcode = request.getParameter("fsubscode"); // get the input fax subscriber code
am_phone = am_pcouncode+"-"+am_pareacode+"-"+am_psubcode;
am_fax = am_fcouncode+"-"+am_fareacode+"-"+am_fsubcode;
telex = request.getParameter("telex"); // get the input telex
mobile = request.getParameter("mobile"); // get the input mobile
email = request.getParameter("email"); // get the input email
notes = request.getParameter("notes"); // get the input notes
String colType[] = {"S","S","S","S","S","S","S","S","S","S","S","S","S","S"};
Vector vec = new Vector();
if (cat.equals("u"))
vec.addElement("am_code"); vec.addElement(code); // add code to vector element
else
curCode = dataBeanObj.getCurrentSerial("id_vms_address_master","am_code","");
vec.addElement("am_code"); vec.addElement(curCode); // Next Serial Generation
vec.addElement("am_name"); vec.addElement(name); // add name to vector element
vec.addElement("am_address_1"); vec.addElement(add1); // add address 1 to vector element
vec.addElement("am_address_2"); vec.addElement(add2); // add address 2 to vector element
vec.addElement("am_address_3"); vec.addElement(add3); // add address 3 to vector element
vec.addElement("am_country"); vec.addElement(country); // add country to vector element
vec.addElement("am_state"); vec.addElement(state); // add state to vector element
vec.addElement("am_zip"); vec.addElement(zip); // add zip to vector element
vec.addElement("am_phone"); vec.addElement(am_phone); // add phone to vector element
vec.addElement("am_fax"); vec.addElement(am_fax); // add fax to vector element
vec.addElement("am_e_mail"); vec.addElement(email); // add email to vector element
vec.addElement("am_notes"); vec.addElement(notes); // add notes to vector element
vec.addElement("am_telex"); vec.addElement(telex); // add telex to vector element
vec.addElement("am_mobile"); vec.addElement(mobile); // add mobile to vector element
if (dataBeanObj.isRecordExists("id_country_master"," where country_code='"+country+"'"))
if (cat.equals("u"))
// update the records
updateFlag = dataBeanObj.updateRecord("id_vms_address_master",vec,colType,"where am_code='"+code+"'");
else
// insert record
updateFlag = dataBeanObj.insertRecordPart("id_vms_address_master",vec,colType);
else
isWrongCountry=true;
%>
The connectionSetup.jsp is as follows:
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%@ page import="allaire.taglib.*" %>
<%
Connection con=null;
PreparedStatement ps = null;
Statement stmt=null;
ResultSet rs=null;
try
String jrunDSN = null, lookupDSN = null;
jrunDSN = request.getParameter("dsnvalue") == null ? "vms_test" : request.getParameter("dsnvalue");
lookupDSN = "java:comp/env/jdbc/" + jrunDSN;
InitialContext ctx = new InitialContext();
DataSource dsn = (DataSource)ctx.lookup(lookupDSN);
try
if (application.getAttribute("connectionapplication") == null)
con = dsn.getConnection();
application.setAttribute("connectionapplication",con);
else
con = (Connection) application.getAttribute("connectionapplication");
stmt = con.createStatement();
catch(Exception e)
con = dsn.getConnection();
application.setAttribute("connectionapplication",con);
catch(Exception e)
out.println("<font face='arial' size='2'><center>Problem with database connection. Please contact your administrator</center></font>");
%>
In Connection setup.jsp u can change as u need.
This is thru JNDI. This works fine for us in our projects.
Bye.
Maybe you are looking for
-
Error while creating service tickets
Hi all, we are facing the followin error when we try to create a service ticket in WEB UI. Version CRM 7 with EhP1 installed. Please find the error details Context initialization failed in view ICCMP_BTPARTNER/PartnerTable of UI Component ICCMP_BTPAR
-
I discovered that iTunes is no longer showing any of my playlists or music I have added from sources other than iTunes. My iPod, which is a 4th Gen Classic, seems fine and has all of my playlists and music. My question is how do I upload my iPod to
-
How to convert a ASHX file format to wsdl
Can anyone tell me how to generate a wsdl file from a ashx file.I don't work in .net framework.Only thing i have is weblogic and i need a client-stub to connect to the webservice.Help is urgent. Thanx in advance Edited by saragadam at 05/02/2007 6:41
-
System.out.println in which log file
We are using weblogic 51 server. We have System.out.println's in the servlets but don't see it in any log file. Which log file would/should it go to.
-
Sounds stop playing when user locks screen on iOS with AIR 3.9 Beta
We built a simple application that should play sounds when in background and when the screen is locked. Since we updated to the latest AIR 3.9 Beta SDK, all sounds stop playing when the user locks the screen on iOS. The sounds resume when the screen