| Java and MySql program example ? |
|
 |
Index ‹ java-programmer
|
- Previous
- 1
- Display xml file in JTree: Select information to be shown in node labelHi there,
I have managed to write a small java program that display an xml file
in a JTree. This was achieved by defining a suitable tree model. THe
program works...somehow. The nodes (elements and texts) are correctly
recognized, and the corresponding branches in the JTree can be opened
and closed. However, when I run the program, all the non-leaf nodes
(e. g. the element nodes) are displayed from the start tag to the end
tag including the tag delimiters. Is there any way to control what is
used as a "node label" in a JTree? Of course that could be done by
brute (e.g. by building the JTree from simple strings) but I believe
that this approach will destroy the tree structure of the underlying
xml file.
I have tried for some time to display xml data in a tree view, and a
java solution seemed to be the most "organic" one. So it would be
great if that program to be really made to work properly. Many thanks
for any idea how to achieve this! Piet
Here is the code:
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
public class XmlTreeDemo extends JFrame {
XmlTreeDemo(String title){
super(title);
try{
DocumentBuilderFactory IDocumentBuilderFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder IDocumentBuilder
= IDocumentBuilderFactory.newDocumentBuilder();
Document IDocument = IDocumentBuilder.parse("c:/test1.xml");
Node root = IDocument.getDocumentElement();
XmlTreeModel model = new XmlTreeModel(root);
JTree IJTree = new JTree();
IJTree.setModel(model);
getContentPane().add(new JScrollPane(IJTree),BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (Exception e){
System.err.println(e);
}
}
public static void main(String[] args){
XmlTreeDemo IJTreeDemo = new XmlTreeDemo("Xml tree demo");
IJTreeDemo.pack();
IJTreeDemo.show();
}
}
class XmlTreeModel implements TreeModel{
protected Node root;
public XmlTreeModel(Node root){
this.root = root;
}
public Object getRoot(){
return (Object)this.root;
}
public boolean isLeaf(Object node){
if ((((Node)node).getNodeType() == 7) || (((Node)node).getNodeType()
== 1)) return false;
return true;
}
public int getChildCount(Object parent){
return ((Node)parent).getChildNodes().getLength();
}
public Object getChild(Object parent,int index){
Node child = ((Node)parent).getChildNodes().item(index);
return (Object)child;
}
public int getIndexOfChild(Object parent, Object child){
NodeList childs = ((Node)parent).getChildNodes();
if (childs.getLength() == 0) return -1;
for (int i=0; i<childs.getLength(); i++){
if (childs.item(i) == (Node)child) return i;
}
return -1;
}
public void valueForPathChanged(TreePath path, Object newValue){
}
public void addTreeModelListener(TreeModelListener l){
}
public void removeTreeModelListener(TreeModelListener l){
}
}
- 2
- Single Threaded EnvironmentHi,
I know this might not be the best place to ask this but.. umm I know
Java is a multithreaded environment. what do you call a single threaded
environment where there are no multiple threads or scheduler? Please
tell me because I can't seem to recall the term :( Is it just "single
threaded environment"? Or is the term something else? Thanks!
Rick
- 11
- 13
- 13
- splitting up huge (1 GB) xml documentsDear all,
I am facing the problem that have to handle XML documents of approx. 1
GB. Do not ask me which sane architecture allows the creation of such
files - I have no control over the creation and have to live with it.
I need to split this massive document up into smaller chunks of valid
XML:
The structure of the XML is quite easy:
<businessHeader>Bla, bla -> only about 10 tags</businessHeader>
<businessInformation>info goes here</businessInformations>
<!--the tag business information is repeated a couple of hundred
thousand times... -->
<businessInformation>info goes here</businessInformations>
<businessFoolter>about 10 tags footer</businessFooter>
My current approach is to use SAX to parse the document and write the
businessInformation into different files. Before that the header gets
inserted into each file and after that the footer.
This obviously consumes quite a lot of time since the entire file is
parsed sequentially.
Can you think about a way of how to speed this process up ? I was
thinking of jumping randomly into the <businessInformation>-section of
the file (Random Access File) and then start parsing from there on with
SAX (potentially in parallell by using threads) but I am not sure if
this works.
Any hint is appreciated.
Cheers
Torsten
- 13
- Web Application Works on Windows, Not on Linux (Needs a file)I've been using a web application to find part numbers and info for an
antique car I've been working on for a while. I used to go to the
manufacturer's website, log in ($20 a year fee, otherwise I'd link to it),
click on the link, and the program would run just fine under Linux.
Recently I upgraded my system (from Ubuntu Edgy to Ubuntu Feisty) and now
this app will run in Firefox on Windows XP but won't run on Linux. Now I
get an error that it can't find the file hpwin32 in the java.library.path.
(The full stack trace is below.)
I searched my hard drives on the WinXP system and there's no trace of this
file, so I'm guessing it's a file on their end that isn't loading. This
worked fine when I was using Java 1.4.2 but won't work now, with Java 6
installed.
Any ideas on what I can do to make this work again? What other info would I
need to provide that might help track this problem down? (The supplier
doesn't officially support Linux, so I can't get help from them.)
Hal
--------------Stack Trace from Error Message--------------
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.sun.javaws.Launcher.executeApplication(Launcher.java:1205)
at com.sun.javaws.Launcher.executeMainClass(Launcher.java:1151)
at com.sun.javaws.Launcher.doLaunchApp(Launcher.java:998)
at com.sun.javaws.Launcher.run(Launcher.java:105)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.UnsatisfiedLinkError: no hpwin32 in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1682)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1030)
at
com.hp.tis.ewo.common.win32.Hpwin32DllLoader.loadLibrary(Hpwin32DllLoader.java:63)
at com.hp.tis.ewo.common.win32.Environment.<clinit>(Environment.java:257)
at com.hp.tis.ewo.setup.ContextController.<init>(ContextController.java:54)
at
com.hp.tis.ewo.setup.cookie.CookieEngine.getWorkshopID(CookieEngine.java:181)
at
com.hp.tis.ewo.clienttools.trigger.CookieTrigger.execute(CookieTrigger.java:89)
at com.hp.tis.ewo.clienttools.trigger.TriggerLoop.run(TriggerLoop.java:82)
at
com.hp.tis.ewo.clienttools.connectivity.http.EwaHttpUrlConnection.getBaseHttpConnection(EwaHttpUrlConnection.java:312)
at
com.hp.tis.ewo.clienttools.connectivity.http.EwaHttpUrlConnection.<init>(EwaHttpUrlConnection.java:251)
at
com.hp.tis.ewo.clienttools.ServiceFactory.getConnection(ServiceFactory.java:165)
at
com.proquest.epc.view.bl.ServerConnectionBL.sendToAppServer(ServerConnectionBL.java:110)
at
com.proquest.epc.view.bl.ServerConnectionBL.sendRequest(ServerConnectionBL.java:65)
at com.proquest.epc.view.rh.LoginRequestor.execute(LoginRequestor.java:24)
at
com.proquest.epc.view.impl.MBEPCApplication.main(MBEPCApplication.java:310)
... 9 more
- 13
- Where to find the Java source files?Hi,
I remember Java source files are installed somewhere and I can take a
look at them. For example, right now I hope to look at JFrame's file,
JFrame.java. I forgot where to it is installed. Could you give me a hint?
Thank you.
- 14
- problem getting the java VM to runPatrick Zesar <email***@***.com> wrote in message news:<405b0a79$0$8016$email***@***.com>...
> i just posted this problem to
> http://forum.java.sun.com/thread.jsp?forum=30&thread=504742&tstart=0&trange=15
> with a reference to this thread here.
I just ran into the same problem. Upgraded two win98se machines to XP
Pro SP1. Prior to applying any hotfixes first thing I did was to
install the 1.4.2_04 jre. I have the same jre running flawlessly on
two preinstalled Dells with xp pro sp1. Very interested in a fix,
will post here if I find it.
- 16
- 16
- Cariage returnHello,
I would like to know if there is a way in my Java application to know what
characters are used in the cariage return of text files on the machine the
application works. Is is 13, 10? Is it 10? is it 13? How can I find this?
Thanks for your input.
Francois
- 16
- ThreadPoolExecutor implementation questionHi,
I have a question about Sun's implementation of
java.util.concurrent.ThreadPoolExecutor, specifically the execute(
Runnable ) method. The runState field is read before the Runnable task
is added to the workQueue (BlockingQueue), however there is no
synchronization in place. It seems that it might be possible for
another thread to invoke shutdown after runState is checked, but before
the task is added to the queue. Is it not then possible that the queue
is cleared by the shutdown process, the executor left as terminated,
only for the task to finally be added to the queue, something like:
Thread 1 | Thread 2
execute( t1 ) |
runState==RUNNING |
| shutdown
| runState=SHUTDOWN
| clear out workQueue
| return
| executor now terminated
|
workQueue.add(t1) |
return |
At this point, t1 is stuck in a queue that will never be cleared, but
no feedback to that effect was given on Thread 1.
Looking at Doug Lea's PooledExecutor at
http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/PooledExecutor.java
I see that PooledExecutor.execute uses a synchronized block which would
prevent the above case from occuring.
Am I missing something?
cheers
Allen
- 16
- Java Applet Background ColorHi,
I am trying to set the background color of my applet to white but it
keeps coming up gray.Strangely when I open the applet on a local web
page (not live on the web), applet viewer (thru eclipse) or even live
on the web from my own home PC it appears white as expected. But from
every other machine that I access it the background is grey. Even when
i run it thru Eclips on other PCs the background is gray.I have tried
to set the background to white by calling
setBackground(Color.white)
and
setBackground(Color.WHITE)
from the init() method. In the HTML that calls the applet i also set
the <body bgcolor=#FFFF></body> and i do the same for the <HEAD>.
However from every other machine that I access my webpage/applet
except my own home PC the background still appears as gray.
Any ideas?
Thanks
WS
- 16
- Cigarette Girl ...Cigarette Girl
http://www.cigarettes--online.com/promo/cigarette-girl.html
Cigarette Girl brands are without a doubt one of the most renowned
tobacco brands
in the market.
Discount Cigarette Girl Store offers cheap discount US made Cigarette
Girl online.
Cigarette Girl, are available at discount prices from our online US
made cigs shop
for immediate shipment. Our cheap Cigarette Girl are delivered to your
door.
More Info here >>>
http://www.cigarettes--online.com/promo/cigarette-girl.html
- 16
- Two questions about jars1) I need to support installing a Java application from CD on both Windows
AND on the Mac. I have figured out how autorun works on Windows. Is the
method for doing this the same on the Mac as it is for Windows? I am
thinking that what I'd do is create an install "program" (like the Setup
program created by Install Shield on Windows), but make it as an executible
jar file so that the Java VM on either can handle the install process. That
way, a single CD should be able to accomodate both the Mac and Windows.
2) I have found the process of making executible jar files a little
problematic, and the documentation from Sun with the SDK a little lacking in
examples: and the documentation with eclipse and Netbeans IDE is a bit of a
maze (I'd have thought that both would make it easy to create executible
jars, but I haven't found the relevant parts of their documentation yet, so
I am still struggling with hat from Sun). I understand that to make a jar
executible, I need to provide a manifest file, but I have yet to succeed in
adding one. Can anyone point me to a simple example of making an executible
jar containing a Swing application, or provide me with one (if that is
simple enough)? (And/or provide a map pointing out the relevant parts of
the documentation I have acquired) I need this jar to be self contained, so
I do not need to worry about what version of the JRE the client machine has.
I guess I ought to add a third question about whether or not either eclipse
or netbean supports making a distribution as an executible jar file that
will install the application on the client machine and create any necessary
directories and icon on the desktop? I have found, though, a couple tools
that should be able to do this, but I haven't been able to test them because
I got stuck on the question of creating executible jar files.
I am certain I can figure this out on my own, but the big problem is I am
facing significant time pressure, so I ask for aide to help me get this
figured out faster.
Thanks,
Ted
- 16
- Mozilla Firefox bookmarks exporting.
Hi,
I use mozilla firefox and feel very comfortable with that. I have
accumulated a lot of interesting websites in my bookmarks. Now if I
want to switch to a other machine how can preserve my old set of
bookmarks?
Thank you in advance,
Shaji.
|
| Author |
Message |
bjornar

|
Posted: 2004-1-14 5:07:00 |
Top |
java-programmer, Java and MySql program example ?
I am trying to learn Java and need an example program with MySql
database.
I am sure there are many who have made an invoice program in Java with
MySql database. The program must have routines that are similar to
those an invoice program has: customers, orders, products. Screens
like orders head and orderlines.
Can you please send me a copy of the source files for such a program
or a different program?
|
| |
|
| |
 |
Tony Morris

|
Posted: 2004-1-14 8:16:00 |
Top |
java-programmer >> Java and MySql program example ?
No.
--
Tony Morris
(BInfTech, Cert 3 I.T., SCJP[1.4], SCJD)
Software Engineer
IBM Australia - Tivoli Security Software
(2003 VTR1000F)
"Bjornar" <email***@***.com> wrote in message
news:email***@***.com...
> I am trying to learn Java and need an example program with MySql
> database.
> I am sure there are many who have made an invoice program in Java with
> MySql database. The program must have routines that are similar to
> those an invoice program has: customers, orders, products. Screens
> like orders head and orderlines.
> Can you please send me a copy of the source files for such a program
> or a different program?
|
| |
|
| |
 |
joe.rabbit

|
Posted: 2004-1-15 0:42:00 |
Top |
java-programmer >> Java and MySql program example ?
email***@***.com (Bjornar) wrote in message news:<email***@***.com>...
> I am trying to learn Java and need an example program with MySql
> database.
> I am sure there are many who have made an invoice program in Java with
> MySql database. The program must have routines that are similar to
> those an invoice program has: customers, orders, products. Screens
> like orders head and orderlines.
> Can you please send me a copy of the source files for such a program
> or a different program?
I did a quick project for class one time and i still have the source
code.
I take it you used a fake address on this post so if you or any one
wants a copy of the code email me at jdanyjavajunkie at yahoo.com
|
| |
|
| |
 |
joe.rabbit

|
Posted: 2004-1-15 2:27:00 |
Top |
java-programmer >> Java and MySql program example ?
email***@***.com (Bjornar) wrote in message news:<email***@***.com>...
> I am trying to learn Java and need an example program with MySql
> database.
> I am sure there are many who have made an invoice program in Java with
> MySql database. The program must have routines that are similar to
> those an invoice program has: customers, orders, products. Screens
> like orders head and orderlines.
> Can you please send me a copy of the source files for such a program
> or a different program?
Try this out, besure to download MySQL JDBC connector from:
http://www.mysql.com/downloads/api-jdbc.html
then to run it type the following at the command line.
java -cp .\;mysql-connector-java-3.0.10-stable-bin.jar TestMySQL
--- cut ---
/*
* TestMySQL.java
*
*/
import java.sql.*;
public class TestMySQL {
public static void main(String argv[]) throws Exception {
// --- Load the driver class.
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
}
catch (Exception ex) {
System.out.println("Can't load driver.");
System.exit(1);
}
// --- Try to connect to MySQL Server.
java.sql.Connection MySQLConnection = null;
try {
/*
The format for a connection string is as follows:
jdbc:mysql: -- Connection type
//my_host -- MySQL Host or IP address.
/my_database -- Database to open
?user=my_user_name -- user name
&password=my_password -- password
*/
MySQLConnection =
java.sql.DriverManager.getConnection(
"jdbc:mysql://localhost/my_database"+
"?user=user&password=my_pass");
}
catch (Exception ex) {
System.out.println(
"Can't connect to MySQL Server.");
System.exit(1);
}
// --- Create table and add Values.
java.sql.Statement SQLStatement =
MySQLConnection.createStatement();
int count;
SQLStatement.executeUpdate (
"DROP TABLE IF EXISTS animal");
SQLStatement.executeUpdate (
"CREATE TABLE animal ("
+ "id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
+ "PRIMARY KEY (id),"
+ "name CHAR(40), category CHAR(40))");
count = SQLStatement.executeUpdate (
"INSERT INTO animal (name, category)"
+ " VALUES"
+ "('snake', 'reptile'),"
+ "('frog', 'amphibian'),"
+ "('tuna', 'fish'),"
+ "('racoon', 'mammal')");
SQLStatement.close ();
System.out.println (count + " rows were inserted");
// --- Show records.
SQLStatement = MySQLConnection.createStatement();
SQLStatement.executeQuery(
"SELECT id, name, category FROM animal");
java.sql.ResultSet SQLResultSet = SQLStatement.getResultSet();
count = 0;
while (SQLResultSet.next()) {
int idVal = SQLResultSet.getInt("id");
String nameVal = SQLResultSet.getString("name");
String catVal = SQLResultSet.getString("category");
System.out.println("id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
SQLResultSet.close();
SQLStatement.close();
System.out.println(count + " rows were retrieved");
// --- Close connection.
MySQLConnection.close();
}
}
-- cut --
Reference material
-- begin --
Writing JDBC Applications with MySQL
Paul DuBois
email***@***.com
Document revision: 1.01
Last update: 2003-01-24
Table of Contents
?Preliminary Requirements
?Connecting to the MySQL Server
?Issuing Queries
o Issuing Queries That Return No Result Set
o Issuing Queries That Return a Result Set
Using Placeholders
o Error Handling
?Resources
?Acknowledgment
You can write MySQL applications in a variety of languages. The
languages that most people use with MySQL are PHP and Perl, but a
sometimes overlooked option is the MySQL Connector/J driver, which
allows you to develop Java applications that interact with your MySQL
server.
MySQL Connector/J works within the framework of the Java JDBC
interface, an API that allows Java programs to use database servers in
a portable way. JDBC is based on an approach similar to that used in
the design of Perl and Ruby DBI modules, Python's DB-API module, and
PHP's PEAR::DB class. This approach uses a two-tier architecture:
?The top level is visible to application programs and presents an
abstract interface for connecting to and using database engines. The
application interface does not depend on details specific to
particular engines.
?The lower level consists of drivers for individual database engines.
Each driver handles the details necessary to map the abstract
application interface onto operations that a specific engine will
understand.
The JDBC interface allows developers to write applications that can be
used with different databases with a minimum of porting effort. Once a
driver for a given server engine is installed, JDBC applications can
communicate with any server of that type. By using MySQL Connector/J,
your Java programs can access MySQL databases.
Note: MySQL Connector/J is the successor to the MM.MySQL driver. If
you have JDBC programs written for MM.MySQL, they should work with
MySQL Connector/J as well, although you may want to update the driver
class name used in your programs. Just replace instances of
org.gjt.mm.mysql in your Java source files with com.mysql.jdbc and
recompile.
Preliminary Requirements
To use Java applications with MySQL, you may need to install some
additional software:
?If you want to compile and run Java programs, you'll need a Java
compiler (such as javac or jikes) and a runtime environment. If these
are not already installed on your system, you can get them by
obtaining a Java Software Development Kit (SDK) from java.sun.com.
?If you want only to run precompiled applications, no compiler is
necessary, but you'll still need a Java Runtime Environment (JRE).
This too may be obtained from java.sun.com.
This article assumes that you'll write and compile your own programs,
and thus that you have a Java SDK installed. Once you compile a Java
program, however, you can deploy it to other machines, even ones that
have only a runtime environment. This works even in heterogenous
installations, because Java is platform-independent. Applications
compiled on one platform can be expected to work on other platforms.
For example, you can develop on a Linux box and deploy on Windows.
Connecting to the MySQL Server
To connect to the MySQL server, register the JDBC driver you plan to
use, then invoke its getConnection() method. The following short
program, Connect.java, shows how to connect to and disconnect from a
server running on the local host. It accesses a database named test,
using a MySQL account with a user name and password of testuser and
testpass:
import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName,
password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database
server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection
terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
Compile Connect.java to produce a class file Connect.class that
contains executable Java code:
% javac Connect.java
Then invoke the class file as follows and it should connect to and
disconnect from your MySQL server:
% java Connect
Database connection established
Database connection terminated
If you have trouble compiling Connect.java, double check that you have
a Java Software Development Kit installed and make sure that the MySQL
Connector/J driver is listed in your CLASSPATH environment variable.
The arguments to getConnection() are the connection URL and the user
name and password of a MySQL account. As illustrated by Connect.java,
JDBC URLs for MySQL consist of jdbc:mysql:// followed by the name of
the MySQL server host and the database name. An alternate syntax for
specifying the user and password is to add them as parameters to the
end of the connection URL:
jdbc:mysql://localhost/test?user=testuser&password=testpass
When you specify a URL using this second format, getConnection()
requires only one argument. For example, the code for connecting to
the MySQL server in Connect.java could have been written like this:
String userName = "testuser";
String password = "testpass";
String url = "jdbc:mysql://localhost/test?user="
+ userName
+ "&password="
+ password;
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url);
getConnect() returns a Connection object that may be used to interact
with MySQL by issuing queries and retrieving their results. (The next
section describes how to do this.) When you're done with the
connection, invoke its close() method to disconnect from the MySQL
server.
To increase the portability of your applications, you can store the
connection parameters (host, database, user name, and password) in a
Java properties file and read the properties at runtime. Then they
need not be listed in the program itself. This allows you to change
the server to which the program connects by editing the properties
file, rather than by having to recompile the program.
Issuing Queries
To process SQL statements in a JDBC-based application, create a
Statement object from your Connection object. Statement objects
support an executeUpdate() method for issuing queries that modify the
database and return no result set, and an executeQuery() method for
queries that do return a result set. The query-processing examples in
this article use the following table, animal, which contains an
integer id column and two string columns, name and category:
CREATE TABLE animal
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id),
name CHAR(40),
category CHAR(40)
)
id is an AUTO_INCREMENT column, so MySQL automatically assigns
successive values 1, 2, 3, ... as records are added to the table.
Issuing Queries That Return No Result Set
The following example obtains a Statement object from the Connection
object, then uses it to create and populate the animal table. DROP
TABLE, CREATE TABLE, and INSERT all are statements that modify the
database, so executeUpdate() is the appropriate method for issuing
them:
Statement s = conn.createStatement ();
int count;
s.executeUpdate ("DROP TABLE IF EXISTS animal");
s.executeUpdate (
"CREATE TABLE animal ("
+ "id INT UNSIGNED NOT NULL AUTO_INCREMENT,"
+ "PRIMARY KEY (id),"
+ "name CHAR(40), category CHAR(40))");
count = s.executeUpdate (
"INSERT INTO animal (name, category)"
+ " VALUES"
+ "('snake', 'reptile'),"
+ "('frog', 'amphibian'),"
+ "('tuna', 'fish'),"
+ "('racoon', 'mammal')");
s.close ();
System.out.println (count + " rows were inserted");
The executeUpdate() method returns the number of rows affected by a
query. As shown above, the count is used to report how many rows the
INSERT statement added to the animal table.
A Statement object may be used to issue several queries. When you're
done with it, invoke its close() method to dispose of the object and
free any resources associated with it.
Issuing Queries That Return a Result Set
For statements such as SELECT queries that retrieve information from
the database, use executeQuery(). After calling this method, create a
ResultSet object and use it to iterate through the rows returned by
your query. The following example shows one way to retrieve the
contents of the animal table:
Statement s = conn.createStatement ();
s.executeQuery ("SELECT id, name, category FROM animal");
ResultSet rs = s.getResultSet ();
int count = 0;
while (rs.next ())
{
int idVal = rs.getInt ("id");
String nameVal = rs.getString ("name");
String catVal = rs.getString ("category");
System.out.println (
"id = " + idVal
+ ", name = " + nameVal
+ ", category = " + catVal);
++count;
}
rs.close ();
s.close ();
System.out.println (count + " rows were retrieved");
executeQuery() does not return a row count, so if you want to know how
many rows a result set contains, you should count them yourself as you
fetch them.
To obtain the column values from each row, invoke getXXX() methods
that match the column data types. The getInt() and getString() methods
used in the preceding example return integer and string values. As the
example shows, these methods may be called using the name of a result
set column. You can also fetch values by position. For the result set
retrieved by the SELECT query in the example, id, name, and category
are at column positions 1, 2 and 3 and thus could have been obtained
like this:
int idVal = rs.getInt (1);
String nameVal = rs.getString (2);
String catVal = rs.getString (3);
ResultSet objects, like Statement objects, should be closed when
you're done with them.
To check whether or not a column value is NULL, invoke the result set
object's wasNull() method after fetching the value. For example, you
could check for a NULL value in the name column like this:
String nameVal = rs.getString ("name");
if (rs.wasNull ())
nameVal = "(no name available)";
Using Placeholders
Sometimes it's necessary to construct queries from values containing
characters that require special treatment. For example, in queries,
string values are written enclosed within quotes, but any quote
characters in the string itself should be doubled or escaped with a
backslash to avoid creating malformed SQL. In this case, it's much
easier to let JDBC handle the escaping for you, rather than fooling
around trying to do so yourself. To use this approach, create a
different kind of statement (a PreparedStatement), and refer to the
data values in the query string by means of placeholder characters.
Then tell JDBC to bind the data values to the placeholders and it will
handle any special characters automatically.
Suppose you have two variables nameVal and catVal from which you want
to create a new record in the animal table. To do so without regard to
whether or not the values contain special characters, issue the query
like this:
PreparedStatement s;
s = conn.prepareStatement (
"INSERT INTO animal (name, category) VALUES(?,?)");
s.setString (1, nameVal);
s.setString (2, catVal);
int count = s.executeUpdate ();
s.close ();
System.out.println (count + " rows were inserted");
The '?' characters in the query string act as placeholders--special
markers indicating where data values should be placed. The setString()
method takes a placeholder position and a string value and binds the
value to the appropriate placeholder, performing any special-character
escaping that may be necessary. The method you use to bind a value
depends on the data type. For example, setString() binds string values
and setInt() binds integer values.
Error Handling
If you want to trap errors, execute your JDBC operations within a try
block and use an exception handler to display information about the
cause of any problems that occur. JDBC provides getMessage() and
getErrorCode() methods that may be invoked when an exception occurs to
obtain the error message and the numeric error code. The following
example deliberately issues a malformed query. When it runs, the
executeQuery() method fails and raises an exception that is handled in
the catch block:
try
{
Statement s = conn.createStatement ();
s.executeQuery ("XYZ"); // issue invalid query
s.close ();
}
catch (SQLException e)
{
System.err.println ("Error message: " + e.getMessage ());
System.err.println ("Error number: " + e.getErrorCode ());
}
Resources
The following sites provide information about the tools discussed in
this article:
?Sun's Java site is a clearinghouse for all kinds of Java-related
information:
? http://java.sun.com/
?
You can obtain the Java Software Development Kit or Java Runtime
Environment here. The specification for the JDBC API is also available
on this site, should you wish to read more about it.
?The MySQL Connector/J driver is supported by MySQL AB. Connector/J
author Mark Matthews maintains the driver, which is available at:
? http://www.mysql.com/
?
?Introductory articles describing other MySQL APIs based on an
architecture similar to that used for JDBC may be found at:
? http://www.kitebird.com/articles/
?
APIs discussed in the articles include Perl DBI, PHP PEAR::DB, Python
DB-API, and Ruby DBI.
Acknowledgment
The original version of this article was written for NuSphere
Corporation. The current version is an updated revision of the
original.
-- End
|
| |
|
| |
 |
| |
 |
Index ‹ java-programmer |
- Next
- 1
- reference to a jar file inside another jar fileHi, I need create a manifest file for a jar, but I need set the classpath in
the manifest file to reference a jar file inside the current jar file. My
idea is getting a single jar file which contains all the needed jar files.
- 2
- Adding JPanel to JLayeredPane - Please help!Hi
I have a problem adding a JPanel to a JLayeredPane.
The class ChartGraphics paints a system of coordinats / Chart on a
JPanel
using the paint() metode. When I add the ChartGraphics object directly
to the Contentpanel of the frame the Chart is shown without any
problems. But as I want to add some buttons on top of the Chart, I
want to place it in a JLayeredPanel, and afterwards add the Jbuttons.
The problem is that the Chart is'nt shown if it is placed in the
JLayeredpane, why? The Button is displayed nicely.
Can anybody tell me how to display my JPanel background from the
JlayeredPane?
/Thanks
Kristian
******************ShowTrendsTest *******************
public class ShowTrendsTest {
public static void main(String[] args) {
JFrame f = new JFrame("ShowTrends");
ChartGraphics Chart = new ChartGraphics();//extends JPanel
JButton button = button("TST"); //Just a JButton
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.add(Chart, new Integer(0));
layeredPane.add(button, new Integer(1));
f.getContentPane().add(layeredPane);
f.pack();
f.show();
}
public static JButton button(String arg){
JButton b1 = new JButton(arg);
b1.setVerticalAlignment(JButton.TOP);
b1.setHorizontalAlignment(JButton.CENTER);
b1.setOpaque(true);
b1.setBackground(Color.red);
b1.setForeground(Color.black);
b1.setBounds(100, 100, 140, 140);
return b1;
}
}
********************************************
- 3
- Mars Rescue Mission ChallengeA new challenge:
http://www.frank-buss.de/marsrescue/index.html
Have fun! Now you can win real prices.
--
Frank Bu? email***@***.com
http://www.frank-buss.de, http://www.it4-systems.de
- 4
- Refer to current filename and line.Hi,
I remember this was possible in C with macros. Is it possible in Java
to refer to the current file name and line number as in
System.out.println( something.that.returns.current.file.name() + "
printed this line.");
Many thanks in advance!
Aaron
- 5
- what the problem about this short code?import javax.media.Manager;
import javax.media.bean.playerbean.MediaPlayer;
import java.lang.String;
public class Player1 {
MediaPlayer mp1 = new MediaPlayer();
public Player1(){
mp1.setMediaLocation(new String("file:\\d:\\music\\11.wma"));
}
public static void main(String[] args){
Player1 player1=new Player1();
player1.mp1.start();
}
}
it says that Cannot find a Player for :file:\d:\music\11.wma.what the
problem?
- 6
- OutOfMemory on Sun Java 1.4.2 on LinuxHi all,
My application (on JBoss) is experiencing strange problem on one of our
environment - on Linux on Itanium 2 - Sun Java 1.4.2_07 and 64 bit.
On all other platforms (windows, linux, 32 bit) is ok.
After 2-3 http requests the OutOfMemory exception is thrown.
Java is started with -Xmx1024M. In fact the bahaviour is exactly the
same as -Xmx512M.
'uname -a' shows unlimited resources for memory.
There is plenty of free memory in the system (main and swap) - for
example I can run 3 such java processes at the same time - but each is
reporting out of memory after few requests as it is for one java spawned.
'top' shows that java eats ~400M when the OutOfMemory is thrown.
Where to look, what to check?
taab
- 7
- 8
- How to kill thread which is blocked by Serversocket.accept()?Hi;
I have got a network-thread running in the background listening for
connection-attempts.
The thread uses an instance of Serversocket and its accept() method to
listen.
After a certain period of time i want to kill the thread if no connection is
established.
The problem is: the accept-method blocks until someone connects.
Therefore it is not possible for me to use the interrupted-flag and check it
within a loop in my
thread to signalize it to end (the recommended way to kill a thread). I dont
want to use the thread.stop
() method since it is deprecated, but even when i try to use it i can not
kill the thread.
Within my gui thread i tried to use a swing timer, but it doesnt kill the
thread:
timer = new Timer(TEN_SECONDS, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (networkThread.isAlive) {
timer.stop();
networkThread.stop();
//...Update the GUI...
}
}
Anybody there who knows a proper way of killing such a blocked thread?
Thanks in advance,
Jan
- 9
- Resizing images thru a java program
hi
I need to capture an image based on the URL of the image provided by
the user and do the following things
1. Create a thumbnail
2. Resize the image
I may have to store these two images locally or just recreate these two
images and display it in the browse.
What are the best tools to use to achieve this? I need a Linux/java
based solution. Will Imagemagick.org do the magic?
-- Mahesh
- 10
- Runtime - external program visibility
Hello,
i use the getRuntime method to start an external program out of
my Java app: Runtime.getRuntime().exec(cmd);
where cmd is an array of String
String[] cmd =
{ "\"c:/Whatever.exe\"","/user=User","/password=XXX"};
Now the issue is that the program (Whatever.exe) starts, it
accepts the parameters (user,password), - the / is required by
Whatever.exe - but the window of the application Whatever.exe is
not visible! The process is there (one can see it in the
taskmanager).
In Delphi i have the possibility by using Windows.CreateProcess
and passing a "StartupInfo"
(lStartupInfo.dwFlags:= STARTF_USESHOWWINDOW;
lStartupInfo.wShowWindow:= SW_SHOWNORMAL;) but here in Java i dont see a possibility of determining in which way the external app is being started up or determining its visibility.
kind regards
Oliver
- 11
- Reference sitesDoes anyone have a list of reference websites that are running FreeBSD
and Java?
Or does anyone know of any high volume sites using FreeBSD and Java?
Thanks,
Todd
_______________________________________________
email***@***.com mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-java
To unsubscribe, send any mail to "email***@***.com"
- 12
- Signed applet focus problem,.Hello,
I have a jsp page which contains a signed applet which reads some
System properties.
I am using jdk 1.4.2_06. and IE 6.028.
When the signed certificate appears, if I click on the Internet
Explorer icon in the task bar, the certificate goes below the browser.
Now since the certificate is supposedly modal, My browser loses focus.
ie. I cannot bring the certificate to the front sans tabbing and the
browser will not respond to user input. The only way to get the
certificate to the front is by "tabbing" till I get to it.
Any one seen this behavior before? If so any suggestion would be
appreciated.
Thanks
Karl.
- 13
- OMLETv4: SPAM SPAM SPAM
--
Daniel A. Morgan
University of Washington
email***@***.com
(replace 'x' with 'u' to respond)
- 14
- Execute jar in program codeI have a jar file, without source code, say abc.jar.
I have set it in the CLASSPATH
The main execute class in abc.jar is a.class.
In the command prompt, I can execute the program by
issuing "java a < someIOfile"
But I would be like to embed it in my program.
Can I create a "dynamic" instance from it?
- 15
- GCJ 4.1 and OpenOffice.orgFWIW, I have been working with Eric Anholt to have Kaffe (java/kaffe)
supported by bsd.java.mk. The only thing with miss is a port of a
Javadoc tool so that ports documentation may be built without any Sun or
IBM JDK. I believe gjdoc (can't remember if this part of classpath or
another "free" Java tool) could be used in place of javadoc.
I'll have a look at your wrapper and modifications in the next few days.
Herve
On Fri, Mar 10, 2006 at 10:59:35AM +0900, NAKATA Maho wrote:
> I believe gcj is now one of the usable Java implementation,
> however there are some small (but tedious) issues must be solved to
> check in to FBSD ports cvs repo.
> I made some ports or updates of ports so that we can at least compile a
> package using Java; OpenOffice.org. I believe with appropreate wrapper,
> we can add gnugcj as _JAVA_VENDOR_LIST in /usr/ports/Mk/bsd.java.mk.
> then we can use/comple Java applications without bootstrapping java/jdk14
> etc.
|
|
|