MYSQL statement
A simple question but cant seem to find the answer anywhere:
I am trying to search my DB via a jsp page and have used a drop down selection box in order to get the specific field within the table for the user to search, and then a text box to allow the searchstring to be entered, so how do you write the sql statement so that it will use the selection box variable which I have managed to save as a string with the correct value of the field/column in the table???
this is what i have:
String Query = "SELECT * FROM member WHERE searchfield = '" + searchstring + "'";
ResultSet SQLResult = SQLStatement.executeQuery(Query);
so how do i format the searchfield variable??
prefix it with $, &, @, ', i have tried a few but they all cause errors and I cant find the answer anywhere else.
Thanks
Brian
I'm not sure if I understand you.
You have the column to search against in a pull-down menu, and the value to search in that column in a text field?
E.g.:
searchfield = Pulldown: name, city, state, zip
searchstring = Text: "enter value for {name, city, state, zip}"
(Without writing the HTML for that)
So, when your JSP executes, you have either "name", "city", "state" or "zip" stored in the String variable "searchfield", and then whatever the user typed stored in the String variable "serachstring". Right?
Your query should read (to be modified later):
query = "SELECT * FROM member WHERE " + searchfield + " = '" + searchstring + "' ";
That's your basic query. If the user selects "city" and enters "Boston", the string will be constructed to appear as:
"SELECT * FROM member WHERE city = 'Boston' "
Now, this isn't sufficient, in general. There may be a way of doing this in JDBC somewhere, I don't know. But I had to write my own code to do it. Essentially, you need to modify "searchfield" to double up any single quotes (apostrophes). Otherwise, the query will choke. E.g., suppose Name = "Thomas O'Neal". Your query will be constructed as:
"SELECT * FROM member WHERE name = 'Thomas O'Neal' "
See how the single-quotes don't mathch up? It looks like "name = 'Thomas O'" followed by extraneous garbage ("Neal"). So you have to convert "Thomas O'Neal" to "Thomas O''Neal", and then it'll work fine.
I hope that helps.
Similar Messages
-
CS4-generated PHP/MySQL Statements
I have constructed a simple 2 program GUI in CS4 using PHP and MySQL. Program A accepts XHTML form user input of two text fields, which are then passed to program B for subsequent MySQL retrieval and processing. I would appreciate a little clairification on the MySQL statement that CS4 generates in the recordset I built.
Here are the PHP statements that set the passed variables in Program B:
$colname1_Recordset1 = "";
if (isset($_POST['transaction_mfgr_importer'])) {
$colname1_Recordset1 = $_POST['transaction_mfgr_importer'];
$colname2_Recordset1 = "";
if (isset($_POST['transaction_model'])) {
$colname2_Recordset1 = $_POST['transaction_model'];
Here is the recordset generated based on that input:
mysql_select_db($database_DGRconnect_acquisition, $DGRconnect_acquisition);
$query_Recordset1 = sprintf("SELECT * FROM dgr_ad_vendor_acquisition WHERE dgr_ad_vendor_acquisition.transaction_mfgr_importer = %s AND dgr_ad_vendor_acquisition.transaction_model = %s", GetSQLValueString($colname1_Recordset1, "text"),GetSQLValueString($colname2_Recordset1, "text"));
$Recordset1 = mysql_query($query_Recordset1, $DGRconnect_acquisition) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
I have highlighted in red the parts of the generated statement from which my questions arise. Basically, I'd like to know how the "%s" is generated to represent the two variables, and more importantly, how they are parsed so that they are differentiated in the statement. In other words, how does the engine keep track of which "%s" is which? I hope my first question isn't about as clear as mud!
Secondly, Is there any way I can manipulate the two of these variables to work in a "LIKE" operand, versus the "=" one?
$query_Recordset1 = sprintf("SELECT * FROM dgr_ad_vendor_acquisition WHERE dgr_ad_vendor_acquisition.transaction_mfgr_importer LIKE %s AND dgr_ad_vendor_acquisition.transaction_model LIKE %s", GetSQLValueString($colname1_Recordset1, "text"),GetSQLValueString($colname2_Recordset1, "text"));
I would prefer to alter my original statement to take advantage of the relative comparison function that the LIKE operand normally performs. I want the resultant rows retrieved by the SELECT to include anything similar to what the user inputed. Normally, the LIKE comparison requires a hard-coded string, eg. "WHERE dgr_ad_vendor_acquisition.transaction_mfgr_importer LIKE '%General Electric%'... ". I'm trying to figure out how to replace the "%s" variable representations with the contents of $colname1_Recordset1 and $colname2_Recordset1 respectively.
Thanks for your time, and any feedback would be greatly appreciated!Sorry about the Scotch whiskey teaser. I saw where a bottle of Bowmore 1850 auctioned for 29,000 English pounds. Sheesh!
As for the PHP imbedded in the SQL, I guess I had hoped that maybe since PHP and MySql seem to be kindred spirits as far as a database/programming platform goes, that maybe Apache/MySQL knew to evaluate the PHP statement within the MySQL statement and somehow convert it. As I said, I had my doubts and they were proven to be true.
In any event, I want to thank you again. Your solution is working swimmingly for me in several of my prototype applications. Much appreciated! -
Writing multiple rows in one line, mysql statement. No strings are saved
Hi, I dont know how to make multiple rows inputs into the table in one sentence. Ive got an error: "java.sql.SQLException: Statement parameter 2 not set" provided by code below. It works fine for one Date row (saves in the db corectly) however when I use for two different date types two single statements it will write databes two times putting 2x Null in the every other row. I dont want that, I need it to be written in one connection and statement.
try{
String userName = "user";
String password = "pass";
String url = "jdbc:mysql://dbadress/dbname";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection (url, userName, password);
Statement st1=con.createStatement();
Date BirthDate = wdContext.currentPeopleElement().getBirthDate(); //People - context node, BirthDate - context attribute
Date FillDate = wdContext.currentContextElement().getFillDate();
String sql1 = "INSERT INTO table1 (BirthDate1,FillDate1) VALUES (?,?)"; //BirthDate1,FillDate1 - rows in the "table1" table
PreparedStatement stmt1 = con.prepareStatement(sql1);
stmt1.setDate(1, BirthDate);
stmt1.setDate(1, FillDate);
stmt1.executeUpdate();
stmt1.close();
catch(Exception e) {
wdComponentAPI.getMessageManager() .reportWarning( e.toString() ); }
I would like to know how to fix it.
Other issue is that code below:
try{
String userName = "user";
String password = "pass";
String url = "jdbc:mysql://dbadress/dbname";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection (url, userName, password);
Statement st1=con.createStatement();
Date BirthDate = wdContext.currentPeopleElement().getBirthDate(); //People - context node, BirthDate - context attribute
String sql1 = "INSERT INTO table1 (BirthDate1) VALUES (?)"; //BirthDate1 row in the "table1" table
PreparedStatement stmt1 = con.prepareStatement(sql1);
stmt1.setDate(1, BirthDate);
stmt1.executeUpdate();
stmt1.close();
catch(Exception e) {
wdComponentAPI.getMessageManager() .reportWarning( e.toString() ); }
works perfectly fine. It does write date in the database as shown on the monitor hoever it doesnt work if we change Date type with String. Of course context nodes are String type as well. Code below will write "Null" value in the db. Dont know why. Of course I write some string down in the input field and save after, just like do it with Date type which works fine. Please advice.
try{
String userName = "user";
String password = "pass";
String url = "jdbc:mysql://dbadress/dbname";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection (url, userName, password);
Statement st2=con.createStatement();
String signature = wdContext.currentContextElement().getsignature(); //signature - context
String sql2 = "INSERT INTO table1 (signature1) VALUES (?)"; //signature1 - name of row in the table1
PreparedStatement stmt2 = con.prepareStatement(sql2);
stmt2.setString(1, signature);
stmt2.executeUpdate();
stmt2.close();
catch(Exception e) {
wdComponentAPI.getMessageManager() .reportWarning( e.toString() ); }
Regards, Blamer.Hi,
Fix for your first issue
I dont know how to make multiple rows inputs into the table in one sentence. Ive got an error: "java.sql.SQLException: Statement parameter 2 not set" provided by code below. It works fine for one Date row (saves in the db corectly) however when I use for two different date types two single statements it will write databes two times putting 2x Null in the every other row. I dont want that, I need it to be written in one connection and statement.
try{
String userName = "user";
String password = "pass";
String url = "jdbc:mysql://dbadress/dbname";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection (url, userName, password);
Statement st1=con.createStatement();
Date BirthDate = wdContext.currentPeopleElement().getBirthDate(); //People - context node, BirthDate - context attribute
Date FillDate = wdContext.currentContextElement().getFillDate();
String sql1 = "INSERT INTO table1 (BirthDate1,FillDate1) VALUES (?,?)"; //BirthDate1,FillDate1 - rows in the "table1" table
PreparedStatement stmt1 = con.prepareStatement(sql1);
stmt1.setDate(1, BirthDate);
stmt1.setDate(1, FillDate);
stmt1.executeUpdate();
stmt1.close();
catch(Exception e) {
wdComponentAPI.getMessageManager() .reportWarning( e.toString() ); }
I would like to know how to fix it.
Change the line stmt1.setDate(1, FillDate); to stmt1.setDate(2, FillDate);
As a workarond for your following issue
works perfectly fine. It does write date in the database as shown on the monitor hoever it doesnt work if we change Date type with String. Of course context nodes are String type as well. Code below will write "Null" value in the db. Dont know why. Of course I write some string down in the input field and save after, just like do it with Date type which works fine. Please advice.
try{
String userName = "user";
String password = "pass";
String url = "jdbc:mysql://dbadress/dbname";
Class.forName ("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection (url, userName, password);
Statement st2=con.createStatement();
String signature = wdContext.currentContextElement().getsignature(); //signature - context
String sql2 = "INSERT INTO table1 (signature1) VALUES (?)"; //signature1 - name of row in the table1
PreparedStatement stmt2 = con.prepareStatement(sql2);
stmt2.setString(1, signature);
stmt2.executeUpdate();
stmt2.close();
catch(Exception e) {
wdComponentAPI.getMessageManager() .reportWarning( e.toString() ); }
Try as follows
PreparedStatement stmt2 = con.prepareStatement(sql2);
stmt2.setString(1, (signature == null ? "Value missing" : signature));
stmt2.executeUpdate();
stmt2.close();
If the context attribute is null it will enter the text "Value Missing",
Regards
Ayyapparaj -
thank's for your reply .Now I have another problem
I use J2EE RI from java.sun .I try to follow example in j2eetutorial about CMP Example call RosterApp.ear .
I dont'change anything code inside RosterApp.ear but when I deploy and runclient command thereis syntax error :
java.rmi.ServerException: Remote exception occured in server thread :nested exception is java.rmi.ServerException :exception thrown from bean :nested exception is : java.ejb.EJBException :nested exception is :java.sql.SQLException :syntax error or access violation ,message from server: "you have an error in SQL syntax near "
"leagueBeanTable" WHERE "leagueId" = 'L1' at line 1
in example ,RosterApp.ear use Cloudscape database ,but I try to use Mysql database for RosterApp.ear ,is there any different syntax SQL from Cloudscape to Mysql .
if like that ,so I must edit first SQL calls from Cloudscape to MYSQL . I think because relationship fields is for entity beans only ,so how if mysql database want to access foreign key another table because foreign key isn't declare in databse table.
example : I have 3 entity bean call player, team, league .
1. PlayerEJB have persistence fields name, position, playerId(primary key), cmr fields is teams
2. TeamEJB have persistence fields name, city, teamId (primary key) , cmr fields is players and leagues .
3. LeagueEJB have persistence fields name ,sport, leagueId(primary key), cmr fields is teams
so table is
PlayerEJB <--->TeamEJB<--->LeagueEJB
Player have some finder method call findBySport(String Sport) .
because Sport is persistence fields for LeagueEJB
so PlayerEJB must traverse TeamEJB first before LeagueEJB
EJB QL : SELECT distinct object(p) FROM Player (p) IN (p.teams) AS t
WHERE t.league.sport = ?1
I know that Container will translates EJB QL to SQL calls ,but default is only for cloudscape database and I use for MYsql .
so can you helpme how to query method findBySport(String sport) to Mysql calls .
thereis no foreign key between table in database table there is only Relationship fields in entity bean.How can I remove the double quotes from PetStore CMP SQL statements?
It seems I am having the sam problem with the PetStore app with J2EE RI and MySQL:
Could not create: nested exception is: java.sql.SQLException: Syntax error or access violation, message from server: "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near '"UserEJBTable" WHERE "userName" = 'j2ee'' at
line 1"
I grabbed then entire sql statement from the MySQL logs:
SELECT "userName" FROM "UserEJBTable" WHERE "userName" = 'j2ee'
I ran this from a MySQL command prompt WITHOUT the double quotes and it works fine. I've tried removing the double quotes from the sun-j2ee-ri.xml files but they still appear in the deployed ear!
Please help,
Will -
Problem with GRANT syntax in MYSQL statement...need help!
Good afternoon all!
I need a little help with some mysql syntax. I'm using version 4.0.17, and I'm just starting to try to learn about connection pooling (you'll probably see future posts from me on this topic as well:)...
I'm following the directions contained on Apache's website (http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html) on how to set up a JNDI datasource.....
The directions are simple, Create a new test user, a new database and a single test table. Your MySQL user must have a password assigned. The driver will fail if you try to connect with an empty password.
I then proceed to enter this line into my mysql prompt - mysql> GRANT ALL PRIVILEGES ON *.* TO javauser@localhost IDENTIFIED BY 'javadude' WITH GRANT OPTION;
Here's the error I get : ERROR 1045: Access denied for user: '@localhost' (Using password: NO)
Can someone give me the heads up on what the "correct" syntax is?tnguyen1973 , I tried your statement again, this time excluding the -p, pressed Enter and then entered the statement I first posted, and it took that too.
So I'm hoping I can now continue with the example provided on the Apache website.
Can you tell me the difference between using the -p in the statement, and where I can learn more about these things?
Thanks. -
Display rows affected data from MySQL statement??
Hi,
Im trying to get the return data from a MySQL database, such as the ROWS AFFECTED into after an INSERT sql command.
Could anyone help me? I mean I know its easy in PHP to use the "mysql_affected_rows" command, but how do you do this in Java?
Many thanks!
SebexecuteUpdate will return the affected row count for insert, update, and delete statements. Is that what you're after?
-
hi,
i have an error with my sql statement and i try to find the error but i couldn't could you please help me to find the error in this statement.
sql.append("SELECT * FROM CARS WHERE TO_DAYS('");
sql.append(PickDat + "') >= TO_DAYS('FROM_D')");
sql.append("AND TO_DAYS('");
sql.append(DropDat + "') <= TO_DAYS('UNTIL_D')");
sql.append("AND PICK_UP_DROP ='");
sql.append(pickdropPnt + "'AND CAR_TYPE ='");
sql.append(carclass + "'");
error message :
java.sql.SQLException: Syntax error or access violation: You have an error in your SQL syntax near '' at line 1 java.sql.SQLException: Syntax error or access violation: You have an error in your SQL syntax near '' at line 1
thanks,
yuetNihi,
thanks for your reply, i tried to use your idea but it still give me an error which i couldn't understand it.
is it ok if i use the code below to convert a String to Date.
java.sql.Date PickDat = java.sql.Date.valueOf(PDate);
java.sql.Date DropDat = java.sql.Date.valueOf(DDate);
System.out.println("IN CARINFO FUNC." + pickdropPnt + PDate + DDate + carclass);
sql.append("SELECT * FROM CARS");
sql.append("WHERE TO_DAYS('" PickDat "') BETWEEN TO_DAYS('FROM_D') AND TO_DAYS('UNTIL_D') ");
sql.append("AND TO_DAYS('" DropDat "') BETWEEN TO_DAYS('"+PickDat+"') AND TO_DAYS('UNTIL_D') ");
sql.append("AND PICK_UP_DROP ='" + pickdropPnt +"' ");
sql.append("AND CAR_TYPE ='"+carclass + "'");
thanks for your help
regards,
yuetNiSwee -
Conditional Mysql select statement
HI Folks
can anyone point me in the right direction with a MySQL statement.
I will try to layout my thinking here:
I have a form with three inputs area, name and search. I am trying to write a Mysql select statement that selects records from a single table if they match the criteria. Easy for two variables but I'm lost after that.
1. The form includes these three inputs:
area - drop down menu (Any as default)
name - drop down menu (Any as default)
search box - text area (Blank as default)
2. The form submits to itself leaving me with these three variables
$search=$_GET['search']
$area=$_GET['area']
$name=$_GET['area']
SELECT * FROM database WHERE database.description LIKE '%$search%' AND database.area LIKE '$area' AND database.name LIKE '$name'
3. This is where I get confused. How do I get the SQL to Select everything correctly. I have tried using PHP if/else code to fix it but I end up running around in circles with six different Select statements and haven't yet got that to work.
So I have come to the conclusion that there must be an easier way. I see search forms with dozens of search criteria on websites every day an d I only have 3 - so it can't be this complicated. Right?
I know I need to start from the beginning again but can anyone let me know how to approach it before I begin?
Cheers
DaveTypically, I would build the where clause dynamically, based upon the values in your form. If the form field contains 'Any', leave it out of the where clause. So you can test each field value and either append or not to the end of the where clause.
-
Statement in Transaction Does Not Roll Back
I have a group of MySQL statements in a method of a Java application.
I include an SQL error in the last statement to test the rollback of the transaction.
All the statements roll back, EXCEPT for the one detailed below.
The MySQL table:
CREATE TABLE Counter (
number INT( 4 ) NOT NULL DEFAULT 0,
account_id VARCHAR( 12 ) NOT NULL PRIMARY KEY
) ENGINE = InnoDB;I have run the staement as a PreparedStatement and a Statement:
PreparedStatement:
String updateCounterStr =
" UPDATE Counter " +
" SET number = number + 1 " +
" WHERE account_id = ? "
updateCounter = con.prepareStatement ( updateCounterStr );
updateCounter.setString( 1, accountID );
int uc = updateCounter.executeUpdate(); Statement:
Statement updateCounterStatement = con.createStatement();
int updatecounter = updateCounterStatement.executeUpdate(
"UPDATE Counter SET number = number + 1 " +
"WHERE account_id = \'" + accountID + "\'"
con.setAutoCommit( true ); // ------------------------------------ Transaction ENDS
updateCounterStatement.close();
// updateCounter.close();
... several more
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
if (con != null) {
try {
System.err.print("Transaction is being ");
System.err.println("rolled back");
con.rollback(); // < ------------------------------------ con.rollback() HERE
} catch(SQLException excep) {
System.err.print("SQLException: ");
System.err.println(excep.getMessage());
} // ---------------------------------------- END the methodIn both cases Counter is incremented, but does NOT roll back.
The other statements in the transaction do roll back,
I am using:
mysql Ver 14.12 Distrib 5.0.18, for apple-darwin8.2.0 (powerpc) using readline 5.0
on Mac OS X 10.4.x
I would greatly appreciate a solution to this problem.
Many thanks in advanceI think autocommit is true by default. Also, it looks like your'e setting it to true, and then executing more SQL.
Explicitly set it to false, and DON'T set it back to trueif there's any chance you're going to want to rollback after that. -
INSERT statement in JSP using variables
People,
I am having problems inserting data from JSP into a MySQL database.
For example the following works perfectly fine:
String query = "INSERT INTO `test2` (`name`, `topic`, `message`) VALUES ('Jane Doe', 'Hi there', 'Example message')";
But, however the problems take place if I try to use variable values as parameters instead of pre-defined strings.
E.g. the following (among a 100 other ways I have tried by now) does not work):
String query = "INSERT INTO `test2` (`name`) VALUES (`" + userName +"`)";
stmt.executeUpdate(query);
This did not work either:
PreparedStatement PStmt = myConn.prepareStatement("insert into (`name`) values (?)");
PStmt.setString(1, new String("`" + userName + "`"));
PStmt.executeUpdate();
I have tried without parenthesis etc. but what I pretty much get every time is:
500 Servlet Exception
java.sql.SQLException: Column not found: Unknown column 'Jane' in 'field
list'
at org.gjt.mm.mysql.MysqlIO.sendCommand(MysqlIO.java:508)
at org.gjt.mm.mysql.MysqlIO.sqlQueryDirect(MysqlIO.java:561)
at org.gjt.mm.mysql.MysqlIO.sqlQuery(MysqlIO.java:646)
at org.gjt.mm.mysql.Connection.execSQL(Connection.java:973)
at org.gjt.mm.mysql.Connection.execSQL(Connection.java:897)
at org.gjt.mm.mysql.Statement.executeUpdate(Statement.java:230)
at org.gjt.mm.mysql.jdbc2.Statement.executeUpdate(Statement.java:99)
at sql3_jsp._jspService(/sql3.jsp:49)
at com.caucho.jsp.JavaPage.service(JavaPage.java:87)
at com.caucho.jsp.JavaPage.subservice(JavaPage.java:81)
at com.caucho.jsp.Page.service(Page.java:474)
at com.caucho.server.http.FilterChainPage.doFilter(FilterChainPage.java:166)
at com.caucho.server.http.Invocation.service(Invocation.java:277)
at com.caucho.server.http.CacheInvocation.service(CacheInvocation.java:129)
at com.caucho.server.http.RunnerRequest.handleRequest(RunnerRequest.java:334)
at com.caucho.server.http.RunnerRequest.handleConnection(RunnerRequest.java:266)
at com.caucho.server.TcpConnection.run(TcpConnection.java:140)
at java.lang.Thread.run(Thread.java:484)
I do not know much about SQL or JDBC but the material I have seen makes me believe
that I am pretty much doing the right thing.
What is the right way of doing this?
I would greatly appreciate any feedback.Hi,
I think i know the problem.
Take a look on your String code :
"INSERT INTO `test2` (`name`, `topic`, `message`) VALUES ('Jane Doe', 'Hi there', 'Example message')";
it is not necessary to put QUOTE for the tablename and the fields.
my code work with :
String query = "INSERT INTO test2 VALUES( ' " + 123 + " ' ) ";
( if you inserting into all fields in your table ) OR
String query = "INSERT INTO test2 ( abc ) VALUES( ' " + 123+ " ' ) ";
( if you need to select certain fields ).
or you can try to refer to :
http://www.w3schools.com/sql/sql_insert.asp
hope this help. -
Can't get jdbc MySQL transactions to work
Hi
I'm trying to get a series of MySQL statements to work as a transaction but I can't get the transaction side to work.
I have the tables set up as InnoDB to support transactions.
My current code is written like this (from after the connection is opened). This method throws SQLException.
Statement statement = connection.createStatement();
String sql = "BEGIN;";
int i = statement.executeUpdate(sql);
// insert row into TABLE persons
sql = "INSERT INTO persons SET " +
"personID='" + p.getPersonID() + "', " +
"firstName='" + p.getFirstName() + "', " +
"lastName='" + p.getLastName() + "', " +
"emailAddress='" + p.getEmailAddress() + "', " +
"password='" + p.getPassword() + "', " +
"approvalRating='" + p.getApprovalRating() + "';";
i = statement.executeUpdate(sql);
// get the address object associated with p
Address a = p.getAddress();
// insert row into TABLE addresses
sql = "INSERT INTO addresses SET " +
"personID='" + a.getPersonID() + "', " +
"address1='" + a.getAddress1() + "', " +
"address2='" + a.getAddress2() + "', " +
"town='" + a.getTown() + "', " +
"city='" + a.getCity() + "', " +
"county='" + a.getCounty() + "', " +
"country='" + a.getCountry() + "', " +
"postcodeArea='" + a.getPostcodeArea() + "', " +
"postcode2='" + a.getPostcode2() + "', " +
"phoneHome='" + a.getPhoneHome() + "', " +
"phoneWork='" + a.getPhoneWork() + "', " +
"phoneMobile='" + a.getPhoneMobile() + "';";
i = statement.executeUpdate(sql);
sql = "COMMIT;";
int i = statement.executeUpdate(sql);When the SQLException is caught, I want to execute a ROLLBACK
I can't seem to get this to work. What am I doing wrong?1.) Which exact exception do you get and at what line?
2.) You should really use PreparedStatements and set the parameters there instead of building a dynamic SQL string, because that's greatly in danger of beeing attacked with a SQL injection attack. See http://en.wikipedia.org/wiki/SQL_injection for details.
3.) You don't need to execute "COMMIT;" as a SQL command, there's connection.commit() for this (make sure that auto-commit is off, using connection.setAutoCommit() if necessary).
Edit: 4.) You don't need to do "BEGIN" as well (what gave you the idea, by the way?) -
Hi
Can anyone tell me how they'd format this MySQL statement to read dates stored in MySQL? The dates are pre-1970 so I'm having trouble using PHP echo date.
$query_rsGNresults = sprintf("SELECT * FROM gemnews_tab WHERE language LIKE %s AND entry LIKE %s AND works LIKE %s AND category LIKE %s ORDER BY date ASC;", GetSQLValueString($varLang_rsGNresults, "text"),GetSQLValueString($varEntry_rsGNresults, "text"),GetSQLValueString($varWorks_rsGNresults, "text"),GetSQLValueString($varCategory_rsGNresults, "text"));
I've tried
$query_rsGNresults = sprintf("SELECT * DATE_FORMAT(date, '%Y %M %d') FROM gemnews_tab WHERE language LIKE %s AND entry LIKE %s AND works LIKE %s AND category LIKE %s ;", GetSQLValueString($varLang_rsGNresults, "text"),GetSQLValueString($varEntry_rsGNresults, "text"),GetSQLValueString($varWorks_rsGNresults, "text"),GetSQLValueString($varCategory_rsGNresults, "text"));
but all I get is a sprintf error that there are too few arguments.
Any help is greatly appreciated.
Many thanks
JHello Mad Dog,
I am sorry that you have not received a response for the
WebAssist
community forums.
The most effective way to get your issue addressed is by
submitting a
Technical Support Incident (PSI) because we have a policy to
provide you
with a response within 2-4 business hours. We include a
number of
Support Incidents for free with each product
If you would like to submit one go to
http://www.webassist.com/ and
click on the Support link on the gray bar above the Product
Spotlight.
On the Support page, choose Support > Technical Support
> Submit
Incident. Select your product and click on the appropriate
radio button
that applies to the nature of your product. Click Next and
fill out the
form on the subsequent page. An engineer should reply back to
you within
2 to 4 hours.
Feel free to contact me off list if you have further
questions.
Regards,
Mark
Mark Fletcher
WebAssist.com
Mad Dog wrote:
> On recommendation of a few people here (yes, Murray, I
do listen to you
> sometimes!) I picked up DataAssist from WebAssist to
create a front-end
> database admin area for a client. Easily worth the money
since it saved me
> hours of gunky work creating one myself and the client
will be paying for
> it. One question though -- and yes, I've posted it on
the WebAssist forum
> but haven't had a response yet:
>
> - It's unwieldy to ask whoever's entering the data to
input the date as
> YYYY-MM-DD when no one thinks that way. Is there a way
to have them input it
> in US style (MM-DD-YYYY) and have it converted? It would
be a nice function
> to have built-in but since it's not, is there an
**easy** way to implement
> this?
>
> Thanks,
> Mad Dog
>
> -
Mm.mysql JDBC Driver and the WHERE clause
Anybody has succesfully performed a MySQL/JDBC query in a JSP application using more than one variable in the WHERE clause?
It works fine when I run queries with one fixed value assigned to a column and one variable assigned to the other column in the WHERE clause; but when I do it with more than one variable in the WHERE clause, it screws up throwing an error.
I wonder if it is a code error, a syntax error or if it is something tricky about the mm.mysql JDBC Driver. Following is a section of the code and the error. The variables are s_description and s_status. I read some examples in a book but they use SQL Server. Thank you in advance for any information.
CODE:
<% String sqlStatement = "" ; %>
<% String s_description = "Mexican Style Rice" ; %>
<% String s_status = "available" ; %>
<% java.sql.Statement stmt = con.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_UPDATABLE); %>
<% java.sql.ResultSet rs ; %>
<% sqlStatement = "SELECT code, description, status FROM products WHERE products.description =" + s_description + " AND products.status =" + s_status + ";" ;%>
<% rs = stmt.executeQuery(sqlStatement); %>
<% rs.beforeFirst(); %>
<% while (rs.next()) { %>
<% rs.updateString(3, "sold"); %>
<% rs.updateRow(); %>
<% }%>
<% rs.close(); %>
This is the ERROR it throws
java.sql.SQLException: Column not found: Unknown column 'available' in 'where clause'
at org.gjt.mm.mysql.MysqlIO.sendCommand(MysqlIO.java:497)
at org.gjt.mm.mysql.MysqlIO.sqlQueryDirect(MysqlIO.java:550)
at org.gjt.mm.mysql.MysqlIO.sqlQuery(MysqlIO.java:635)
at org.gjt.mm.mysql.Connection.execSQL(Connection.java:882)
at org.gjt.mm.mysql.Connection.execSQL(Connection.java:815)
at org.gjt.mm.mysql.Statement.executeQuery(Statement.java:169)
at org.gjt.mm.mysql.jdbc2.Statement.executeQuery(Statement.java:78)
at pagecompile._GetFood_xjsp._jspService(_GetFood_xjsp.java:45)
at com.newatlanta.servletexec.JSP10HttpJspPage.service(JSP10HttpJspPage.java:41)
at com.newatlanta.servletexec.JSP10Servlet.service(JSP10Servlet.java:779)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.newatlanta.servletexec.ServletExec.CallServletService(ServletExec.java:1679)
at com.newatlanta.servletexec.ServletExec.processServletRequest(ServletExec.java:1654)
at com.newatlanta.servletexec.ServletExec.processServletAlias(ServletExec.java:1602)
at com.newatlanta.servletexec.ServletExec.ProcessRequest(ServletExec.java:1343)
at com.newatlanta.servletexec.ServletExec.ProcessRequest(ServletExec.java:1113)I think perhaps this sentence has problems:
<% sqlStatement = "SELECT code, description, status FROM products WHERE products.description =" + s_description + " AND products.status =" + s_status + ";" ;%>
You can
<% sqlStatement = "SELECT code, description, status FROM products WHERE products.description ='" + s_description + "' AND products.status = '" + s_status + "'" ;%>
You perhaps ignore the ���� when using String variable s_description and s_status.
Hope this will help you. Good lucky! -
Insert a mysql resultset to a jTable
Hi! I have a database which i can connect to and get information from, but i can't figure out how to insert my resultset into my jTable from two different classes, I found an good exaple on the web but i dont know how to split up the code. I work with the GUI editor in NEtbeans 6.8 since i'm most familiar with it.
I have bound an jButton (that lies in Class A) that will call an method in Class B which will update the jTable.
The action event code
//Creates object "b" from the class ClassB
ClassB b = new ClassB();
try {
//Call method showall in ClassB
b.showall();
} catch (ClassNotFoundException ex) {
System.out.println("Class not found);
{code}
And here is the method "showall"
{code}
String sql = "my sql query";
ResultSet rs = dc.query(sql);
Object[] rows;
while (rs.next()) {
//add the values to the temporary row
rows = new Object[]{rs.getInt(0), rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)};
// add the temp row to the table
// Startup is the name of my mainclass wich i have the jTable in (named "table")
Startup.table.setValueAt(rows, 1, 1);
{code}
This is the example i found
{code}
class MySQLTable
private static Connection con = null;
private static String URL = "jdbc:mysql://localhost:3306";
private static String driver = "com.mysql.jdbc.Driver";
private static String user = "root";
private static String pass = "";
* Main aplication entry point
* @param args
* @throws SQLException
public static void main(String[] args) throws SQLException
// a MySQL statement
Statement stmt;
// a MySQL query
String query;
// the results from a MySQL query
ResultSet rs;
// 2 dimension array to hold table contents
// it holds temp values for now
Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3"}};
// array to hold column names
Object columnNames[] = {"ID", "User", "Password"};
// create a table model and table based on it
DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);
JTable table = new JTable(mTableModel);
// try and connect to the database
try {
Class.forName(driver).newInstance();
con = DriverManager.getConnection(URL, user,pass);
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
// run the desired query
query = "SELECT ID, User, Password FROM users.normal";
// make a statement with the server
stmt = con.createStatement();
// execute the query and return the result
rs = stmt.executeQuery(query);
// create the gui
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
// remove the temp row
mTableModel.removeRow(0);
// create a temporary object array to hold the result for each row
Object[] rows;
// for each row returned
while (rs.next()) {
// add the values to the temporary row
rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3)};
// add the temp row to the table
mTableModel.addRow(rows);
private MySQLTable()
{code}
I would appreciate some help with this :)I am now close to my goal, no errors when i run my application but nothing happens to the jTable
Here is the code for the method
public void gettableinfo() throws ClassNotFoundException, SQLException{
String sql = "sql query";
ResultSet rs = DatabaseConnection.query(sql);
Object[] rows;
Startup.mTableModel.removeRow(0);
while (rs.next()) {
//add the values to the temporary row
System.out.println(rs.getRow());
rows = new Object[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)};
// add the temp row to the table
Startup.mTableModel.addRow(rows);
}rs.getrow(); finds 12 rows, as i have in my database. but it dosent add the result to the table
the code for the jTable:
static Object rowData[][] = {{"Row1-Column1", "Row1-Column2", "Row1-Column3","Row1-Column4","Row1-Column5"}};
// array to hold column names
static Object columnNames[] = {"ID", "Name", "Info", "Type", "Material"};
public static DefaultTableModel mTableModel = new DefaultTableModel(rowData, columnNames);since i'm using the netbeans GUI editor it makes it a little more complicated. I've set the Jtable as public static and the "table = new JTable(mTableModel);" as followed in the example. It still dont work.
Any ideas? -
Hi
How i can remove the following compilation error to get a connection with mySql...........
test3.java:19: cannot access Statement
bad class file: .\Statement.class class file contains wrong class: org.gjt.mm.mysql.Statement Please remove or make sure it appears in the correct subdirectory of the classpath.
Statement stmt = con.createStatement();
thanks in advance ^sounds like u have a corrupted class file in the connectorJ! just download it again and remove teh jar from teh zip top level directory... put THAT in teh classpath
Maybe you are looking for
-
How to pass the page item data from tabA to TabB of a discoverer report
I have a discoverer repoort, it is master_detail (Dept-Emp) report TabA is a master worksheet, which has a page item Deptno (the data is from a customized query) TabB is detail report which has a Deptno as the page item which show the emp detail info
-
Multiple Catalogs with Photoshop Album Starter Edition 3.0?
Is it possible to work with multiple and independent catalogs in PSA SE? I suppose all catalog information by default is stores in the file C:\Documents and Settings\All Users\Application Data\Adobe\Photoshop Album\Catalogs\My Catalog.psa (Windows XP
-
Using custom tables in jdeveloper
Hi, I've created a custom table using toad. I created the table in applsys and created a synonym to apps. I've also grant all the priveledges to apps as well. However, when I create a query OA to query a standard table eg. PER_ALL_PEOPLE_F, I have no
-
How do I load a copy of CC programs on second Mac?
I have logged out on ain computer, but when logging in to CC on the other get a system error!
-
Re: Error message oxc19a0020
I have received the Error Message Oxc19a0020 on an HP Officejet Pro 6835 that I have had only 2 mos. I have gone through all the steps (turn off, on, unplug power cord, replace ink cartridges, yada yada) and am still getting the message. My printhea