| FazBrowse Wikipedia Viewer | Main Page | | |
| Viewing: https://en.wikipedia.org/wiki/Java_Database_Connectivity |
| JDBC | |
|---|---|
| Developer | Oracle Corporation |
| java.sql and UPDATE and java.sql.Statement – sent to the database server each and every time. In other words, the java.sql.Statement methods are executed using SQL statements to obtain a java.sql.ResultSet object containing the data.
JDBC connections are often managed via a connection pool rather than obtained directly from the driver, like javax.sql.DataSource. ExampleseditWhen a Java application needs a database connection, one of the DriverManager.getConnection() methods is used to create a JDBC java.sql.Connection. The URL used is dependent upon the particular database and JDBC driver. It will always begin with the jdbc: protocol, but the rest is up to the particular vendor. importjava.sql.Statement;
try(Statementstmt=conn.createStatement()){
stmt.executeUpdate("INSERT INTO MyTable(name) VALUES ('my name')");
}
Note that java.sql.Connections, java.sql.Statements, and java.sql.ResultSets often tie up operating system resources such as sockets or file descriptors. In the case of java.sql.Connections to remote database servers, further resources are tied up on the server, e.g. cursors for currently open java.sql.ResultSets. It is vital to close() any JDBC object as soon as it has played its part; garbage collection should not be relied upon. The above try-with-resources construct is a code pattern that obviates this. Data is retrieved from the database using a database query mechanism. The example below shows creating a statement and executing a query. SQLException. There is typically very little one can do to recover from such an error, apart from logging it with as much detail as possible. It is recommended that the java.sql.SQLException be translated into an application domain exception (an unchecked one) that eventually results in a transaction rollback and a notification to the user.
The following code is an example of a database transaction:
External linkseditWikimedia Commons has media related to JDBC. Wikibooks has a book on the topic of: Java Programming/Database Programming
| |