I recently checked in a first cut of a JavaFX scripting framework for Java Database Connectivity, JDBC. This can be found at the openjfx-compiler project. The framework is located in the javafx.sql package of the runtime jar, javafxrt.jar. To get started, use the javafx.sql.DB class.
There are two ways to create a connection to the database, one with a javax.sql.Datasource, and one with the traditional Database URL/user/password combination. For the DataSource method, first create the Datasource or locate one via JNDI.
For MySQL, the class is either com.mysql.jdbc.jdbc2.optional.MysqlDataSource or com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource. Descriptions of these can be found in the MySQL Connector/J documentation. For other databases, check the specific JDBC documentation to see how a DataSource is supported. To create a javafx.sql.DB object using a DataSource, use an Object Literal while setting the dataSource property.
var dataSource = com.mysql.jdbc.jdbc2.optional.MysqlDataSource{};
dataSource.setServerName("localhost");
dataSource.setDatabaseName("fxtest");
dataSource.setUser("jclarke");
var db = DB {
dataSource: dataSource
}
To use the classical approach to open a JDBC connection, provide a database URL, and optional user and password attributes. The following opens the database connection using the same properties as used in the DataSource example above.
var db = DB{
user: 'jclarke'
dbUrl: "jdbc:mysql://localhost/fxtest";
};
If you have a problem connecting, and exception will print.
To execute an SQL statement, use the execute or executeUpdate methods. These do the exact same things, but execute returns a boolean indicating rows have been updated, while executeUpdate returns the number of rows actually updated. Using examples from the JDBC Tutorial, let's first create some tables:
db.execute("drop table if exists COFFEES");
db.execute("drop table if exists SUPPLIERS");
db.execute("create table SUPPLIERS " +
"(SUP_ID INTEGER NOT NULL, " +
"SUP_NAME VARCHAR(40), " +
"STREET VARCHAR(40), " +
"CITY VARCHAR(20), " +
"STATE CHAR(2), " +
"ZIP CHAR(5), " +
"primary key(SUP_ID))");
db.execute("create table COFFEES " +
"(COF_NAME varchar(32) NOT NULL, " +
"SUP_ID int, " +
"PRICE float, " +
"SALES int, " +
"TOTAL int, " +
"primary key(COF_NAME), " +
"foreign key(SUP_ID) references SUPPLIERSPK)");
This is pretty straight forward. Now let's stuff some data into the tables:
db.executeUpdate("insert into SUPPLIERS " +
"values(49, 'Superior Coffee', '1 Party Place', " +
"'Mendocino', 'CA', '95460')");
var values = ["Kona", "00049", "15.99", "0", "0"];
db.execute("insert into COFFEES values(?,?,?,?,?)", values);
The first form is just a literal string, however, the second form uses a Parametrized SQL statement with the values taken from a JavaFX String Sequence. You could also have used the JavaFX String substitution syntax:
var coffee = "Kona";
var supId = 49;
var price = 15.99
var sales = 0;
var total = 0;
db.execute("insert into SUPPLIERS values('{coffee}', {supId), {price}, {sales}, {total}");
To fetch the data use the "query" method.
db.query("select COF_NAME, PRICE from COFFEES where COF_NAME = '{values[0]}'",
function(rs:java.sql.ResultSet):Void {
System.out.println("::{rs.getString("COF_NAME")} {%5.2f rs.getFloat("PRICE")}")
});Using this form of the query method, the function parameter defines a function that takes a java.sql.ResultSet as an argument and is called once for each row of the result. Another form of query returns the ResultSet directly.
It is also possible to get at the basic JDBC objects. The following example show getting a PreparedStatement then using JavaFX Sequences to update rows in the COFFEES table.
var updateString = "update COFFEES " +
"set SALES = ? where COF_NAME like ?";
var updateSales = db.getPreparedStatement(updateString);
var salesForWeek = [175, 150, 60, 155, 90, 100];
var coffees = ["Colombian", "French_Roast", "Espresso",
"Colombian_Decaf", "French_Roast_Decaf", "Kona"];
for(c in coffees) {
updateSales.setInt(1, salesForWeek[indexof c]);
updateSales.setString(2, c);
updateSales.executeUpdate();
}
This is just a start to the JDBC framework in JavaFX script and the entire Tutorial.fx script can be downloaded from here.
Once the JavaFX reflection API is completed, I want to add mappings from SQL directly to and from JavaFX Objects. This will provide the ability to some really interesting things with database access.
I think you should remove all examples of easy constructing of SQL queries, where simple string concatenations and variable substitutions (bindings) are used. Yes, they look pretty but this is just not safe. Why create more good examples of a bad examples, where SQL injections just wait to rear their ugly heads?
Please consider making use of PreparedStatements even more natural and easy, and do not provide examples of queries without prepared statements unless really necessary. And even if so, please make sure you show an alternative code that uses PreparedStatement for comparison. Or as the very last resort, please explain *EVERY TIME* (people may read only excerpts of the docs) why it's important to validate all the input that is passed to the underlying database.
You don't believe me? Then how about me putting into some JavaFX login form following values:
Login: [admin'; --]
Password: [] (empty)
while the background SQL is like this:
db.query("select USER_NAME, USER_PASS from USERS where USER_NAME = '{values[0]}' and USER_PASS = '{values[1]}'",
Hint: the [';--] in SQL means: end the current query [;] and treat the rest as a comment [--]. So I might have just logged into the application without knowing the password, and just by guessing the account name ('admin' is a very typical login, just look at the GlassFish).
This would never happen if PreparedStatement was used!
As a side note, I'm tired of repeating the same to all my students (I'm a university teacher).
With best regards,
Wiktor Wandachowicz
Posted by Wiktor Wandachowicz on May 03, 2008 at 06:11 PM EDT #
@Wiktor Wandachowicz:
Hello Wiktor, I think that mr.clarkeman just to give simple example how to make a connection with JDBC, it doesn't matter if you give better examples to your student, but in my opinion, todays proggrammer must know about SQL injection theirself, because they can more understand about how it happen..
regrads
Wildan
Posted by whiledan on May 17, 2008 at 09:09 PM EDT #
What an arrogant bullshit you are Mr.whiledan.
Posted by 123.236.223.115 on May 21, 2008 at 05:07 PM EDT #
I think you are the one who is bullshit Wiktor. Wildan is right. Not all programmers can easily understand if you give a better example. The SIMPLER, the BETTER... You need to teach them from the basic and easy examples. Don't force them to try advance codes if they do not know the basics... OK?
Posted by gdpags5 on July 09, 2008 at 10:53 PM EDT #
I agree with wiledan & gdpags5.
Professional developers (java or not) MUST know about such things as routine SOP.
Posted by donlow on July 25, 2008 at 02:18 PM EDT #
I've just downloaded Netbeans 6.1. with JAVAFX Plugin.
I cannot find the class
import javafx.sql.*.
I'm a real beginner both in Java and Javafx.
I don't understand where I'm wrong.
Thanks for your samples anyway.
Henry
Posted by HenryMiller on August 18, 2008 at 05:16 AM EDT #
I try to use netbeans 6.1 for a web application with jsf like framework.
I declare a dropdown list for a table.
1) when i use a java programmme (using postgres) who read a table with 3000 tuples, this execution take 3 seconds.
2) when the drop down this take 10 seconds?
My question is why?
Posted by ongaro on November 05, 2008 at 06:16 AM EST #
well Mr hoity toity University teacher Wiktor Wandachowicz.
Wildan showed the basics, move from there.
at least he did something, THOSE THAT CAN DO, THOSE THAT CAN'T TEACH. And it is quite apparent in which category you fall.
There is nothing more nausiating than an academic who has never done any prodcution work himself dictating how it "should be".
get a real job.
Posted by Cam W on January 25, 2009 at 07:55 AM EST #
Advanced example with sourcecode
http://jfxstudio.wordpress.com/2009/05/25/the-graphic-database-front-end-ii/
Posted by surikov on May 26, 2009 at 09:30 AM EDT #
hi
i want to use frame in javafx .but its not working javafx with netbean 6.5.1.and how can i use javafx ui package in same . plz suggest me how to do .
Posted by banita on June 13, 2009 at 08:37 AM EDT #