Database programming best practices (in particular: Java/JDBC)

Status
Not open for further replies.

Tuborg

Ars Tribunus Militum
2,911
I'm working on a research oriented task at work which is generating a lot of structured data. The sort of analysis we want to do screams RDBMS, so I've been doing my best to stuff everything into one. I have a very firm grasp of set theory and a fuzzy understanding of what SQL can do. I bought a book and am learning. Unfortunately, I have nobody at work to discuss this with.

I don't think a persistence framework is the right way to go. As I said, the normalized data is very structured and easy to model. But our "business objects" aren't very well defined. Depending on the particular algorithm we want to run, we may need to query the data in a different format... again, we're still in the research stage. Instead, I intend to create "data access" types as the needs arise and also focus on visualization. There's also not a lot of need for a CRUD-type operation. So I've been coding SQL directly, as a learning exercise and because I believe (maybe mistakenly) that those frameworks solve a different problem than I have.

I'm working in Java with JDBC and H2. Postgres installer kept bombing on me and embedded is easy since I'm the only one coding right now. I'm trying to get insight in two areas: how to manage the "SQL mixed in code" problem and JDBC best practices.

So the first one is more of an architecture question. How do you handle databases (even in other languages)? SQL in code? Lots of stored procedures? Persistence framework? SQL in text files? I'm just not sure what to do.

In the second question, I'm looking for the idioms as well as beginner problems to avoid in JDBC. For instance, I didn't know that ResultSet even had a close() method.

This is getting long... I'll add more questions as I think of them. Thanks!
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
How do you handle databases (even in other languages)? SQL in code? Lots of stored procedures? Persistence framework? SQL in text files? I'm just not sure what to do.
There's quite a few ways to skin a cat here.

Many people advocate putting any sort of complex joining structures into views or stored procedures and having the only bit of 'logic' accessible to the sql code in the user's control being the projection (which columns to get) and the filtering (which rows to include). For many applications I think this is a sensible design, but it requires upfront effort and may not be the best way for the sort of ad hgoc querying you're talking about.

If you are putting significant amounts of raw sql in your code be very careful about whether you place externally sourced 'strings' directly into the queries. If you do this you should always be using prepared statements (there is a strong case to be made that you should simply always use prepared statements without some compelling reason not to) to avoid sql injection attacks (even if initially you aren't accepting external inputs there's no tellnig what might happen to your code in future - save yourself the hassle and do this right from the start.

I personally strongly dislike sql queries in separate files that are read then executed. If you have no need to change it without a recompile then just embed the strings directly in your code. It makes it easier to read and more obvious what is going on (rather than kidding yourself you are 'enterprisey' for doing that). If you are following the initial guideline of placing most of the complexity in a view/stored procedure you would change that aspect in the db anyway rather than the application.

It is always somewhat worrying if you are using a DB but with very 'wishy washy' idea of how the data is strutured. This can lead to serious issues down the line as successive layers of 'band aiding' is layer on in disparate places in code, resulting in the database no longer being (to quote a regular here) "a repository of facts".

The stronger you make the rules and structures in your database the easier life will be down the road. The initial effort to do this will almost certainly pay off, sometimes quicker than you think.

I agree that, form your description, that a persistence layer is not the way to go. But without a fair bit more detail I couldn't really give you much more concrete advice.

In the second question, I'm looking for the idioms as well as beginner problems to avoid in JDBC. For instance, I didn't know that ResultSet even had a close() method.

Pretty much every db operation that creates some non trivial object in JDBC requires the disposable of the result.

The correct idiom for this in java is:

Code:
Statement stmt = conn.createStatement();
try 
{
    ResultSet rs = stmt.executeQuery( "SELECT * FROM MyTable" );
    try 
    {
        while ( rs.next() ) 
        {
            ...
        }
    }
    finally 
    {
        rs.close();
    }
} 
finally 
{
    stmt.close();
}
(I hated the verbosity of this in Java and love c#'s using blocks which represent this idiom far better IMO.)

for some general starting guide to the most basic aspects of using JDBC the wikipedia entry is actually not too bad.
 

warmachine

Ars Tribunus Militum
2,479
Subscriptor
What he said. I still use JBoss 4, which uses the EJB 2.1 persistence model but that's probably not suitable for you. Hibernate is a simpler persistence framework. If that's overengineering, use embedded SQL as it's simpler. Stored procedures are just another language to learn and run-time editable SQL suggests a need for portability, which is better handled by a persistence framework anyway.

I find it very odd that the business model is not well defined but the database is normalised and structured. One should be easily derived from the other. I regard DB design as the business model with implementation details such as column size, relationship tables and indices. Are you sure you don't have gross redundancy in the DB design?
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Tuborg":3jbfeayn said:
I'm working in Java with JDBC and H2. Postgres installer kept bombing on me and embedded is easy since I'm the only one coding right now. I'm trying to get insight in two areas: how to manage the "SQL mixed in code" problem and JDBC best practices.
Except that your data definitions and what options are available to you in terms of how you model the data change greatly depending on what RDBMS you use. You need to really research and decide on one first.

So the first one is more of an architecture question. How do you handle databases (even in other languages)? SQL in code? Lots of stored procedures? Persistence framework? SQL in text files? I'm just not sure what to do.
Build a strong and usable data API from the database to simplify the query logic in the application. By doing this, you'll identify what information the application needs from the database and how to best deliver it. Persistence frameworks can then relive the tedium of making the queries, but my experience has been they just replace one tedium for another.

In the second question, I'm looking for the idioms as well as beginner problems to avoid in JDBC. For instance, I didn't know that ResultSet even had a close() method.
Then read and follow the javadocs closely. Don't leak resources. Remember that Connections typically can only be used from one thread at a time, and can only have one Statement/ResultSet outstanding. It may be worthwhile to use one of the many connection pool libraries to aid in managing them, especially in a threaded application.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
warmachine":1m6evbso said:
I find it very odd that the business model is not well defined but the database is normalised and structured. One should be easily derived from the other.
Nope. My data is well-defined and normalized, and all the data analysis I do require ad-hoc queries of some sort. I'm not sure why the notion that there are many, many ways to analyze some data (such that all of them can't be readied enumerated, much less coded) is surprising to someone.

Consider, for example, if his system is storing sensor measurements or some other sort of scientific data.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
warmachine":o63jjvjp said:
Stored procedures are just another language to learn
No, it isn't. Certain operations can only be done efficiently via stored procedures and/or UDF. For anything resemlbing a complicated data model, they're an absolute necessity.

and run-time editable SQL suggests a need for portability, which is better handled by a persistence framework anyway.
I've never seen a system that allowed the users to write "raw" SQL and that was database portable in any interesting fashion. Giving them that ability will essentially tie your hands.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Remember that Connections typically can only be used from one thread at a time, and can only have one Statement/ResultSet outstanding.

This is sometyhing that is worth checking out in advance.

Oracle in JDBC (at least when I used it) was completely happy with you having multiple statements active on the same cnonection (though ech could only have one result set).

Moving to Sql Server and ADO.Net later was very painful as this is not supported at all unless you enable something called MARS (Multiple Active Result Sets) which is only available in 2005 onwards (and has certain restrictions).

Thus the selection of what database you are suing may significantly alter how you code against it at a pretty high level.
 

Rowan

Ars Tribunus Militum
1,629
What are you trying to do with the Java software? If you just want a pretty interface for CRUD operations there are many existing SQL front-end (TOAD, Oracle's SQL developer, etc). Also, if your analysis requires custom raw SQL then the best tool might be... raw custom SQL you write. The above-mentioned tools will also help with that.

If the Java software you are building is more of an integration tool then you might want to look at a couple of free ETL tools, as those are meant to take all manner of data, massage it and put it to database. (IIRC Talend and Pentaho are two that are worth checking out).
 

Tuborg

Ars Tribunus Militum
2,911
ShuggyCoUk-

Thanks for the Java tips. As I'm used to saying by now, damn Java and its lack of automated deterministic resource management! Here's to hoping Java 7 makes it out the door some day.

The main reason I wanted to store SQL outside of source code was for formatting. It's sort of a pain to read/edit complex queries in string literals.

LordHunter317":3kxdprfr said:
Tuborg":3kxdprfr said:
I'm working in Java with JDBC and H2. Postgres installer kept bombing on me and embedded is easy since I'm the only one coding right now. I'm trying to get insight in two areas: how to manage the "SQL mixed in code" problem and JDBC best practices.
Except that your data definitions and what options are available to you in terms of how you model the data change greatly depending on what RDBMS you use. You need to really research and decide on one first.

I think I'm starting to understand this. For instance, I believe the date handling in H2 is a little hokey. So does the SQL standard not cover the specific data types a DB must provide? Would you mind providing some examples of constraints which are imposed by choice of a DB?

LordHunter317":3kxdprfr said:
So the first one is more of an architecture question. How do you handle databases (even in other languages)? SQL in code? Lots of stored procedures? Persistence framework? SQL in text files? I'm just not sure what to do.
Build a strong and usable data API from the database to simplify the query logic in the application. By doing this, you'll identify what information the application needs from the database and how to best deliver it. Persistence frameworks can then relive the tedium of making the queries, but my experience has been they just replace one tedium for another.

That was my gut feeling about persistence frameworks, too. I do have the beginnings of a clean data access API, but it's a little messy under the hood (hence these questions).

LordHunter317":3kxdprfr said:
warmachine":3kxdprfr said:
I find it very odd that the business model is not well defined but the database is normalised and structured. One should be easily derived from the other.
Nope. My data is well-defined and normalized, and all the data analysis I do require ad-hoc queries of some sort. I'm not sure why the notion that there are many, many ways to analyze some data (such that all of them can't be readied enumerated, much less coded) is surprising to someone.

Consider, for example, if his system is storing sensor measurements or some other sort of scientific data.

Welcome to the world of research software development! Here's a bunch of data and some money, now go do something! LH's example is very apt.


I'll look into connection pool libraries.

Rowan":3kxdprfr said:
What are you trying to do with the Java software? If you just want a pretty interface for CRUD operations there are many existing SQL front-end (TOAD, Oracle's SQL developer, etc). Also, if your analysis requires custom raw SQL then the best tool might be... raw custom SQL you write. The above-mentioned tools will also help with that.

If the Java software you are building is more of an integration tool then you might want to look at a couple of free ETL tools, as those are meant to take all manner of data, massage it and put it to database. (IIRC Talend and Pentaho are two that are worth checking out).

I have a bunch of time series and other temporal data. Then we have numerous scripts which generate analysis of the data using various algorithms. The tool will run some yet-to-be defined machine learning algorithms on a yet-to-be determined subset of that data, then store the results back in the database. The GUI part of the tool will hopefully provide a nice exposition of the inferences drawn by the analysis. Almost all of the updating will be machine generated. The user will primarily supply input in the form of query/visualization options.

Actually, I'm using Weka and have run across the Pentaho forums in previous Googling. Will give a second look.

Thanks, again!
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
Tuborg":tyuz584k said:
So does the SQL standard not cover the specific data types a DB must provide?
It does to a degree, but it doesn't cover everything you might want (no spatial/GIS types, for example), but more importantly, everyone deviates from the standard differently, even on things as fundamental as data types.

Would you mind providing some examples of constraints which are imposed by choice of a DB?
Sure. This is not an exhaustive list, so don't consider it as such:
  • Restrictions on the length / data type for PRIMARY KEY column(s). For example, in MS SQL Server, the primary key may not be more than 900 bytes across all columns that make up the PRIMARY KEY.
  • Restrictions on data size: number of rows/table, length of a row, number of columns/table, etc.
  • Choice of language for writing stored procedures/functions. Limitations in what they can do (e.g., number of triggers per table)
  • Behavior of FOREIGN KEY constraints: not all databases support ON UPDATE / ON DELETE and many have limitations in what support they provide
  • Available index types and functionality. Some support aggregate indexes, computed indexes, and other such functionality.
  • Support for "fancy" views like computed views, updatable views / INSTEAD OF views, and arbitrary rules
Whether you need or don't need any of these things is another story entirely. The list is quite extensive, what I recommend you do is look at the databases that interest you and then decide based on what features they provide if they are adequate for your needs. If not, ask and hopefully someone can provide a recommendation.

However, the biggest place they vary is in syntax, especially for data definition queries. As such, don't expect a CREATE TABLE you write for one database to be usable in another, unless it's very simplistic. This is rarely more than a minor issue, but hopefully it illustrates to you just how vast the differences can be. It really depends on what you're trying to do and what you're trying to model.

Welcome to the world of research software development! Here's a bunch of data and some money, now go do something! LH's example is very apt.
It's like I know or something ;)
 
D

Deleted member 43669

Guest
There is stuff out there that can ease writing SQL-heavy code in Java.

I can suggest Spring's JDBC support. It brings the following to the table:

  • Easy writing of leak-less code. It either dumps ResultSets into List<Map<String,Object>> or provides methods to apply functors to resulting rows
  • Sane, concise methods for executing queries
  • Fixes minor annoyances with JDBC
  • Let's you write parameterized queries using named parameters

You might also want to consider iBatis, which lets you define queries outside Java code (continuous String concatenation is no fun), although I'm tempted lately to roll my own.
 

Drizzt321

Ars Legatus Legionis
34,929
Subscriptor++
LordHunter317":348y21b1 said:
Then read and follow the javadocs closely. Don't leak resources. Remember that Connections typically can only be used from one thread at a time, and can only have one Statement/ResultSet outstanding. It may be worthwhile to use one of the many connection pool libraries to aid in managing them, especially in a threaded application.

+++++ on this. I've been burnt by leaked resources before. My fault, but still. I also agree with using a connection pooling library (I use the Apache/Commons one, no issues). Make sure you close the ResultSet, Statement, and Connection in a finally clause. Personally, I do something like this:


Code:
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
   conn = getConnection();
   stmt = conn.createStatment();
   rs = stmt.executeQuery(query);

   while( rs.next() {
      //Do your work here
   }
} finally {
   try{
      if( rs != null ) {
         rs.close();
      }
   } catch( SQLException ignore ) { //ignore }
   try{
      if( stmt!= null ) {
         stmt.close();
      }
   } catch( SQLException ignore ) { //ignore }
   try{
      if( conn != null ) {
         conn.close();
      }
   } catch( SQLException ignore ) { //ignore }
}


It's generally safe to ignore those exceptions from the close() methods. If I recall from the Javadoc (I could be wrong), the documentation specifically says it probably isn't necessary to handle them. Double check to be sure though.
 

Redshift

Ars Scholae Palatinae
1,260
Has anyone actually run into a problem by not calling close on the resultset, when close IS called on the statement. I've always taken the following (from java.sql.Statement, see the final note) at face value, and have found it to be true with all JDBC drivers used so far:

Code:
    /**
     * Releases this Statement object's database 
     * and JDBC resources immediately instead of waiting for
     * this to happen when it is automatically closed.
     * It is generally good practice to release resources as soon as
     * you are finished with them to avoid tying up database
     * resources.
     * <P>
     * Calling the method close on a Statement
     * object that is already closed has no effect.
     * <P>
     * <B>Note:</B>When a Statement object is 
     * closed, its current ResultSet object, if one exists, is 
     * also closed.  
     *
     * @exception SQLException if a database access error occurs
     */
    void close() throws SQLException;
 
Drizzt321 said:
Code:
   try{
      if( rs != null ) {
         rs.close();
      }
   } catch( SQLException ignore ) { //ignore }
This is DbUtils.closeQuietly, which has several variants. Your example would be:

Code:
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
   conn = getConnection();
   stmt = conn.createStatment();
   rs = stmt.executeQuery(query);

   while( rs.next() {
      //Do your work here
   }
} finally {
   DbUtils.closeQuietly(conn, stmt, rs);
}
 

Prototyped

Ars Legatus Legionis
11,126
Have a set of classes that contain the SQL you expect to use that can be invoked via the methods. This forms your data access layer whose sole purpose is to primarily deal with persistence related to one particular aspect of your application. You can use or build a data access class hierarchy that handles the transaction initiation and commit or rollback, parameter binding, resultset iteration, etc.

Have a set of classes that instantiate and invoke these data access objects. These invoking classes have the overarching logic of what you're trying to do with the data—make decisions, perform processing, save information. This is your business logic tier.

Have a set of classes that aggregate and invoke these business logic objects. Their function is validation of input and error handling, ensuring that the right error conditions get passed back to the caller the right way (an appropriate exception, logging, etc.) This is your service layer.

This lets you have an appropriate view of what's going on at each level.
 

Cossix

Smack-Fu Master, in training
77
Whatever you do, don't try implementing your own persistence model, and try to figure out if some of the stuff you're doing is already implemented in your RDBMS. We have a terrible framework in the office that some web programmer implemented that we're almost stuck with that is just horribly inefficient and basically just reimplements an RDBMS on top of an RDBMS.

Wherever you can, put your validation in the database instead of in the application. You can put it in the app too if you want, but by putting it in the database you're actually sure that the data there is valid. There are lots of projects where this isn't done, and the thought is always "just don't have them connect to the database, have them use the app," but inevitably some CIO or VP or customer wants/needs access to the core system, or the validation gets mucked up in the app, and now your data confidence is plummeting like crazy. If you KNOW a column should always be in a certain range, enforce it as much as you can.
 

Deleterious

Ars Tribunus Militum
2,353
Subscriptor
In general, I find preparedStatements far more useful than the pure SQL-concat version. No only does it allow reuse but it also prevents SQL injections.

Code:
public Object get(Integer id) {
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            Object object = null;

            String query = "SELECT * FROM TABLE WHERE ID=?";
            stmt = connection.prepareStatement(query);
            stmt.setInteger(1, id);
            rs = stmt.executeQuery();
            if (rs.next()) {
                object = new Object();
                object.setId(rs.getLong("ID"));
            }
            rs.close();
            stmt.close();
            return location;
        } catch (Exception e) {
            //Handle the Exception - typically SQLException 
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e) {
                //Handle the Exception
            }
        }
    }

In the above example, if you had some number of ids you could simply keep calling

Code:
            stmt.setInteger(1, newId);
            rs = stmt.executeQuery();
            if (rs.next()) {
                object = new Object();
                object.setId(rs.getLong("ID"));
                objList.add(object);
            }
 
Deleterious":3mopc3bn said:
In general, I find preparedStatements far more useful than the pure SQL-concat version. No only does it allow reuse but it also prevents SQL injections.
Of course you should use prepared statements to avoid SQL injections but I don't think they increase reuse if they're in the application code. You could just as easily have a procedure taking some parameters and concatenating them in a query; you could then pass in whatever values you want. In fact, with string concatenation you can parameterize table and column names, which you can't normally do with prepared statements, so prepared statements are actually more restrictive.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
newwb":15vgm4y2 said:
Of course you should use prepared statements to avoid SQL injections but I don't think they increase reuse if they're in the application code.
They increase reuse on the database side for many databases, it doesn't have to recompute query plans or repeat the parsing, it simply binds the new parameters into the existing query and repeats its execution. I suspect most applications have little utility for this, and the savings are usually small, but still sometimes worth it.

You could just as easily have a procedure taking some parameters and concatenating them in a query; you could then pass in whatever values you want.
Err yes, you could, but it's irrelevant. Reuse is low because there's rarely a need to run the same query multiple times with different parameters within the same execution context and has nothing to do with any limitations or inherent difficultly with prepared statements.

In fact, with string concatenation you can parameterize table and column names, which you can't normally do with prepared statements, so prepared statements are actually more restrictive.
By this logic, dynamically constructing every last SQL statement is the least restrictive way of them all!
 

Deleterious

Ars Tribunus Militum
2,353
Subscriptor
Of course you should use prepared statements to avoid SQL injections but I don't think they increase reuse if they're in the application code. You could just as easily have a procedure taking some parameters and concatenating them in a query; you could then pass in whatever values you want.

1) I agree with LordHunter317 that the reuse bit isn't used very often - but it is available with PreparedStatements and not with standard Statements. Even if you only use it once it's once more than you could have otherwise.
2) Isn't "passing in whatever value you want" one of the risk behaviors for SQL Injections? PreparedStatements not only sanitize input but also strongly type your inputted parameters - Both very good things, IMO.

In fact, with string concatenation you can parameterize table and column names, which you can't normally do with prepared statements,

Um, sure you can. connection.prepareStatement(String) takes a String as an argument - there's nothing to say you can't change the base query String based on passed arguments of table and field names before making a PreparedStatement out of it. Why you'd want to is a question I'd be left with. Getters by and large don't seem to show much performance gain between returning 3 fields and all fields for most subjectively "Normal" sized tables. Inserts/Updates could possibly benefit from updating just the fields you want - but again the performance gain of updating 2 fields vs all of them doesn't seem to be much - and if you update "all" of them there's never a question about Object/Record conformance.

-Del
 
LordHunter317":28rvlsgh said:
They increase reuse on the database side for many databases, it doesn't have to recompute query plans or repeat the parsing, it simply binds the new parameters into the existing query and repeats its execution. I suspect most applications have little utility for this, and the savings are usually small, but still sometimes worth it.
We were clearly talking about code reuse, not caching.

Err yes, you could, but it's irrelevant. Reuse is low because there's rarely a need to run the same query multiple times with different parameters within the same execution context and has nothing to do with any limitations or inherent difficultly with prepared statements.
That statement doesn't at all counter what I said. I was speaking in general; you are speaking of the typical case.

By this logic, dynamically constructing every last SQL statement is the least restrictive way of them all!
Yes it is. However, note that I didn't advocate doing this.
 
Deleterious":1knpt4fw said:
1) I agree with LordHunter317 that the reuse bit isn't used very often - but it is available with PreparedStatements and not with standard Statements. Even if you only use it once it's once more than you could have otherwise.
Yes but again, LH's assertion did not counter mine. String concatenation is more general than using a prepared statement. To achieve the same amount of generality with a prepared statement, you need to combine it with string concatenation. Nothing about those statements has anything to do with frequency with which you require that generality.

2) Isn't "passing in whatever value you want" one of the risk behaviors for SQL Injections? PreparedStatements not only sanitize input but also strongly type your inputted parameters - Both very good things, IMO.
Yes, and I never advocated string concatenation. I would only use it in rare cases and consciously so, and the values concatenated into the query wouldn't come from user input.

Um, sure you can. connection.prepareStatement(String) takes a String as an argument - there's nothing to say you can't change the base query String based on passed arguments of table and field names before making a PreparedStatement out of it.
Yes, but then you're using string concatenation.

Why you'd want to is a question I'd be left with.
It certainly isn't common, but it can be used to apply certain logic to multiple tables. For example, you might want to write general code that deletes from table x when column y equals value z, where x, y, and z are parameters. It's not a common situation but it occurs. Nonetheless, utility is irrelevant to my original argument.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
newwb":39y03d65 said:
We were clearly talking about code reuse, not caching.
You (and only you) might have been, but not one else was. The "reuse" benefit of prepared statements extends beyond mere code reuse, and the fact you were unaware of that doesn't suddenly mean were were only talking about "code reuse". It also means that any discussion that considers just code reuse is automatically wrong. The fact you call what happens on the database "caching" is pretty bloody telling, I think.

That statement doesn't at all counter what I said.
Yes, it does. The implication is that string concatenation somehow magically increases reuse, yet you've never explained how this is the case. I'm pointing out that reuse is simply rare because there's no need, not because of any negative property of prepared statements. You know, the entirely obvious reality of the situation if you've ever accessed a database even once by code.

Likewise, the same counter applies to the claim, 'string concatenation is more general and therefore increases reuse'. That one just has the added bonus of being false and absurd. Even if I somehow bought that writing out:
Code:
query1 = Database.query("charles", "foo, bar, baz", "WHERE foo = arg1 AND bar < arg2 and baz > arg3") // First is table
query1 = Database.query("babbage", "foo, bar, baz", "WHERE foo = arg1 AND bar < arg2 and baz > arg3")
somehow increased reuse over:
Code:
query1 = new PreparedStatement("SELECT foo, bar, baz FROM charles WHERE ...");
// You can figure out the rest
it's an entirely specious argument because it doesn't look at the whole problem. String concatenation by itself isn't enough to produce a working query, because you still have to consider:
  • Validating user-input
  • Handling character encoding issues (which for many databases, is necessarily joined with the first)
  • Doing whatever client-side data conversions are necessary
PreparedStatements in Java handle at least the first one always, normally the second, and frequently the third. String concatenation, by itself, does none of those. The execution call may or may not do anything. The fact you've gotten no meaningful reuse out of the code is just icing on the cake, really.

As such, looking at one small part of what goes and on drawing the conclusion "string concatenation" is more general is absurd. Handling everything you must handle and you'll end up writing something that looks suspiciously like PreparedStatement. You still have to handle character encoding issues, you still have to validate and sanitize user input, and you still have to perform any necessary client-side data conversions before executing the query. All three of which are much harder than what you've "gained" us.

String concatenation is more general than using a prepared statement.
No, it isn't, despite what you believe. In fact, for most databases, string concatenation alone doesn't work correctly. You can't build a functional query simply through string concatenation.

To achieve the same amount of generality with a prepared statement, you need to combine it with string concatenation.
The combination of A and B is not just A.

Yes, and I never advocated string concatenation.
Yes, you did, by calling it "more general" and spinning that in a positive light.

It certainly isn't common, but it can be used to apply certain logic to multiple tables. For example, you might want to write general code that deletes from table x when column y equals value z, where x, y, and z are parameter
And no competent programmer would use merely string concatenation for such an exercise, because it almost assuredly won't work, in the general case.
 
LordHunter317":2q4hyavu said:
You (and only you) might have been, but not one else was.
Read the post I replied to. It's clear that the poster is talking about code reuse.

The "reuse" benefit of prepared statements extends beyond mere code reuse, and the fact you were unaware of that doesn't suddenly mean were were only talking about "code reuse". It also means that any discussion that considers just code reuse is automatically wrong. The fact you call what happens on the database "caching" is pretty bloody telling, I think.
I'm perfectly aware that databases can cache the execution plan of a prepared statement for further use with the same prepared statement.

Yes, it does. The implication is that string concatenation somehow magically increases reuse, yet you've never explained how this is the case. I'm pointing out that reuse is simply rare because there's no need, not because of any negative property of prepared statements. You know, the entirely obvious reality of the situation if you've ever accessed a database even once by code.
I have explained how this is the case: you can parametrize table and column names with string concatenation. Hell, given that SQL queries are sent to the database as strings, you can do anything through the SQL API with SQL strings, and therefore with string concatenation. Part of the point of prepared statements is to restrict what can be done to prevent exploits, unintended behavior, etc. That should be the end of this discussion but I'm sure you'll try to pick apart what I say regardless.

Likewise, the same counter applies to the claim, 'string concatenation is more general and therefore increases reuse'. That one just has the added bonus of being false and absurd. Even if I somehow bought that writing out:
Code:
query1 = Database.query("charles", "foo, bar, baz", "WHERE foo = arg1 AND bar < arg2 and baz > arg3") // First is table
query1 = Database.query("babbage", "foo, bar, baz", "WHERE foo = arg1 AND bar < arg2 and baz > arg3")
somehow increased reuse over:
Code:
query1 = new PreparedStatement("SELECT foo, bar, baz FROM charles WHERE ...");
// You can figure out the rest
it's an entirely specious argument because it doesn't look at the whole problem. String concatenation by itself isn't enough to produce a working query, because you still have to consider:
  • Validating user-input
  • Handling character encoding issues (which for many databases, is necessarily joined with the first)
  • Doing whatever client-side data conversions are necessary
PreparedStatements in Java handle at least the first one always, normally the second, and frequently the third. String concatenation, by itself, does none of those. The execution call may or may not do anything. The fact you've gotten no meaningful reuse out of the code is just icing on the cake, really.
Except that all of those examples of things that prepared statements do for you can be done without them. On the other hand, in general you simply cannot do certain things with prepared statements that you can do with string concatenation.

As such, looking at one small part of what goes and on drawing the conclusion "string concatenation" is more general is absurd. Handling everything you must handle and you'll end up writing something that looks suspiciously like PreparedStatement. You still have to handle character encoding issues, you still have to validate and sanitize user input, and you still have to perform any necessary client-side data conversions before executing the query. All three of which are much harder than what you've "gained" us.
It depends on the use case. In the situations in which I would use string concatenation, none of those tasks are necessary.

The combination of A and B is not just A.
I'm aware of that. The point is that you have to resort to A to do B yet you don't have to resort to B to do A.

Yes, you did, by calling it "more general" and spinning that in a positive light.
:rolleyes: You take me literally when it suits you and read into me when it suits you. Pick one.

And no competent programmer would use merely string concatenation for such an exercise, because it almost assuredly won't work, in the general case.
Obviously, but I never said it was completely general.
 

topham

Ars Legatus Legionis
13,756
Subscriptor
Prepared statements != String Concatenation in any sense.

If you think of prepared statements as a concatenated SQL statement that's handled for you, fine; but it's missing a ton of details and is a complete misunderstanding of what's going on under the hood in any modern database.

If you submit a string (SQL statement) to a typical database it will run that query with zero optimizations except a base execution plan.
If you submit a prepared statement not only do you get a full execution plan generated but it is entirely possible it will be further optimized the -next- time it is run. It will likely pull the data from a cache if it hasn't changed in the mean time and the cache will be kept around. A one-off SQL statement will generally be turfed in very short order and cache related to it has the highest priority of being dumped. These differences can be very significant in an application environment when there are dozens, hundreds, or more people interacting with the database via the application. This is particularly the case for those small queries used to updated various widgets and drop downs that are context sensitive.
 

Deleterious

Ars Tribunus Militum
2,353
Subscriptor
newwb":3hilwbw9 said:
LordHunter317":3hilwbw9 said:
You (and only you) might have been, but not one else was.
Read the post I replied to. It's clear that the poster is talking about code reuse.

To be wholly clear, as the poster you quoted I can state that I intended nothing of the kind. My intent was to detail the type of re-iteration that LH is referring to. Sorry if this wasn't clear. In rereading your reply I can see how we're talking about two completely different things. I would even go so far as to agree with you that PreparedStatements in no way increase code reuse over normal Statements.

-Del
 
Deleterious":lqg9guok said:
To be wholly clear, as the poster you quoted I can state that I intended nothing of the kind. My intent was to detail the type of re-iteration that LH is referring to. Sorry if this wasn't clear.

-Del
Apologies then, I retract my statements about what you said. I interpreted your statement as referring to code reuse because your code example focused on it.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
topham":2uilouti said:
If you submit a string (SQL statement) to a typical database it will run that query with zero optimizations except a base execution plan.
If you submit a prepared statement not only do you get a full execution plan generated but it is entirely possible it will be further optimized the -next- time it is run. It will likely pull the data from a cache if it hasn't changed in the mean time and the cache will be kept around. A one-off SQL statement will generally be turfed in very short order and cache related to it has the highest priority of being dumped.
None of this is true for any full-featured database I can think of. Ad-hoc queries definitely get full execution plans, query caching, results caching, and the like. Some of the details may change (prepared statements might have higher cache priority, for example) but even that is generally not true. The only definite difference is a need to avoid reparsing the SQL every time you submit.
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
newwb":16yqlxij said:
I'm perfectly aware that databases can cache the execution plan of a prepared statement for further use with the same prepared statement.
Then you wouldn't has assumed his comments were solely about "code reuse" and called what happens on the database side "caching". Because, in general, it's not caching the execution plan, you actually hold open database resources.

I have explained how this is the case: you can parametrize table and column names with string concatenation.
Which doesn't improve reuse, because that's not everything involved in submitting a query. It's fundamentally a fallacious argument because you're ignoring steps that must be considered.

Hell, given that SQL queries are sent to the database as strings, you can do anything through the SQL API with SQL strings, and therefore with string concatenation.
No, that's not true depending on the database, the driver, and a whole other bunch of factors. PostgreSQL, for example, prefers all the parameters to be sent as binary. In most databases, some data must always be sent in a "binary" form, it cannot be sent as a string.

Part of the point of prepared statements is to restrict what can be done to prevent exploits, unintended behavior, etc.
Not really, or they wouldn't take strings as the "query" input to be interpolated. I mean, sure, it's an added benefit and the one most people reap, but their principal purpose is not actually security as they are designed. If the goal of the database driver was to make it very difficult/impossible for malicious user input to mess up our data, query interfaces would look substantially different.

Except that all of those examples of things that prepared statements do for you can be done without them.
Sure, if you want to rewrite the PreparedStatement class. That's what you'll end up doing, after all.

On the other hand, in general you simply cannot do certain things with prepared statements that you can do with string concatenation.
The fact that I can't use a prepared statement to do string interpolation along certain parts of a query string doesn't mean that string concatenation is somehow more general that using prepared statements. String concatenation, by itself, cannot assemble me a legal query at all, with most databases, for most queries! On top of that, even if string concatenation were more general and it could assemble me legal queries by itself, you still haven't enabled anything that could substantively be called code reuse, over using PreparedStatements correctly.

It depends on the use case.
It does not depend on the use case, because we're solving the problem in general. You have to prove the case in general, or you haven't proven anything at all.

In the situations in which I would use string concatenation, none of those tasks are necessary.
Charset encoding conversions are always necessary.

I'm aware of that.
No, you're not, because you attempted to make your case by using both together.

The point is that you have to resort to A to do B yet you don't have to resort to B to do A.
No, this statement is simply false. Prepared queries involve more than just string concatenation under the covers. The execution of anything but the simplest SQL query in the simplest situations involves more than just string concatenation under the covers. You cannot achieve B merely through A, so it's fallacious to claim A is more general than B.

:rolleyes: You take me literally when it suits you and read into me when it suits you. Pick one.
No, I'll interpret you in whatever way makes your argument most consistent. The only consistent argument means you were approving the use of string concatenation over prepared statements. Your inability to consider the ramifications of your argument doesn't change what you have done.

Obviously, but I never said it was completely general.
You said it was more general, which is enough. Moreover, that's exactly the sort of case you were implying they ought to be used for!
 

LordHunter317

Ars Legatus Legionis
22,394
Subscriptor
newwb":3ghrykfr said:
Yes, the advantages of prepared statements are compelling enough that I consistently recommend them. How LH interprets my statements in this thread as endorsing using string concatenation in any but rare circumstances is baffling.
The best part is those links don't even show consistent advocacy, but your ability to be a parrot in the past doesn't excuse or change what you've said here and now.
 
Status
Not open for further replies.