Java/Database SQL JDBC/Transaction
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
Demo MySql Transaction
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class MainClass {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url = "jdbc:mysql://localhost/hrapp";
connection = DriverManager.getConnection(url, "username", "password");
statement = connection.createStatement();
String employees1SQL = "UPDATE employees SET " + "num_dependants = 4 "
+ "WHERE employee_id = 123456";
statement.executeUpdate(employees1SQL);
String employees2SQL = "UPDATE employees SET " + "num_dependants = 4 "
+ "WHERE employee_id = 123457";
statement.executeUpdate(employees2SQL);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
}
}
}
}
}
JDBC Transaction
/*
MySQL and Java Developer"s Guide
Mark Matthews, Jim Cole, Joseph D. Gradecki
Publisher Wiley,
Published February 2003,
ISBN 0471269239
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
public class Transaction {
Connection connection;
public Transaction() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager
.getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
} catch (Exception e) {
System.err.println("Unable to find and load driver");
System.exit(1);
}
}
public void doWork() {
try {
java.util.Date now = new java.util.Date();
connection.setAutoCommit(false);
Statement statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = statement
.executeQuery("SELECT * FROM acc_add WHERE acc_id = 1034055 and ts = 0");
// set old row ts = current time
rs.next();
rs.updateTimestamp("ts", new Timestamp(now.getTime()));
rs.updateRow();
rs.moveToInsertRow();
rs.updateInt("add_id", rs.getInt("add_id"));
rs.updateInt("acc_id", rs.getInt("acc_id"));
rs.updateString("name", rs.getString("name"));
rs.updateString("address1", "555 East South Street");
rs.updateString("address2", "");
rs.updateString("address3", "");
rs.updateString("city", rs.getString("city"));
rs.updateString("state", rs.getString("state"));
rs.updateString("zip", rs.getString("zip"));
rs.updateTimestamp("ts", new Timestamp(0));
rs.updateTimestamp("act_ts", new Timestamp(now.getTime()));
rs.insertRow();
connection.rumit();
rs.close();
statement.close();
connection.close();
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException error) {
}
e.printStackTrace();
}
}
public static void main(String[] args) {
Transaction trans = new Transaction();
trans.doWork();
}
}
Test Supports Transactions
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
public class TestSupportsTransactions {
public static boolean supportsTransactions(Connection conn) throws SQLException {
if (conn == null) {
return false;
}
DatabaseMetaData dbMetaData = conn.getMetaData();
if (dbMetaData == null) {
// metadata is not supported
return false;
}
return dbMetaData.supportsTransactions();
}
public static Connection getOracleConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:scorpian";
String username = "userName";
String password = "pass";
Class.forName(driver); // load Oracle driver
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args)throws Exception {
Connection conn = getOracleConnection();
try {
System.out.println("conn=" + conn);
System.out.println("Transaction Support:" + supportsTransactions(conn));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Transaction Info
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. All rights
* reserved. Software written by Ian F. Darwin and others. $Id: LICENSE,v 1.8
* 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer. 2. Redistributions in
* binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee cup"
* logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.sql.Connection;
import java.sql.DriverManager;
public class TXInfo {
public static void main(String[] a) throws Exception {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MusicVideo");
int tx = con.getMetaData().getDefaultTransactionIsolation();
String txtxt = null;
switch (tx) {
case Connection.TRANSACTION_NONE:
txtxt = "TRANSACTION_NONE";
break;
case Connection.TRANSACTION_READ_COMMITTED:
txtxt = "TRANSACTION_READ_COMMITTED";
break;
case Connection.TRANSACTION_READ_UNCOMMITTED:
txtxt = "TRANSACTION_READ_UNCOMMITTED";
break;
case Connection.TRANSACTION_REPEATABLE_READ:
txtxt = "TRANSACTION_REPEATABLE_READ";
break;
case Connection.TRANSACTION_SERIALIZABLE:
txtxt = "TRANSACTION_SERIALIZABLE";
break;
default:
txtxt = "UNKNOWN!!";
}
System.out.println(txtxt);
con.setTransactionIsolation(tx);
System.out.println("Done");
con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
System.out.println("TX is now " + con.getTransactionIsolation());
}
}
Transaction Pairs
/*
Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
Use of this software is authorized pursuant to the terms of the license found at
http://developer.java.sun.ru/berkeley_license.html.
Copyright 2003 Sun Microsystems, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistribution of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistribution in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
Neither the name of Sun Microsystems, Inc. or the names of contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
This software is provided "AS IS," without a warranty of any kind.
ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICORSYSTEMS, INC. ("SUN")
AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN
IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
You acknowledge that this software is not designed, licensed or intended for
use in the design, construction, operation or maintenance of any nuclear
facility.
*/
/*
* Copyright 2003 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* Use of this software is authorized pursuant to the terms of the license found at
* http://developer.java.sun.ru/berkeley_license.html.
*/
import java.sql.*;
public class TransactionPairs {
public static void main(String args[]) {
String url = "jdbc:mySubprotocol:myDataSource";
Connection con = null;
Statement stmt;
PreparedStatement updateSales;
PreparedStatement updateTotal;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement = "update COFFEES " +
"set TOTAL = TOTAL + ? where COF_NAME = ?";
String query = "select COF_NAME, SALES, TOTAL from COFFEES";
try {
Class.forName("myDriver.ClassName");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url,
"myLogin", "myPassword");
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast",
"Espresso", "Colombian_Decaf",
"French_Roast_Decaf"};
int len = coffees.length;
con.setAutoCommit(false);
for (int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
updateTotal.setInt(1, salesForWeek[i]);
updateTotal.setString(2, coffees[i]);
updateTotal.executeUpdate();
con.rumit();
}
con.setAutoCommit(true);
updateSales.close();
updateTotal.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String c = rs.getString("COF_NAME");
int s = rs.getInt("SALES");
int t = rs.getInt("TOTAL");
System.out.println(c + " " + s + " " + t);
}
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
if (con != null) {
try {
System.err.print("Transaction is being ");
System.err.println("rolled back");
con.rollback();
} catch(SQLException excep) {
System.err.print("SQLException: ");
System.err.println(excep.getMessage());
}
}
}
}
}
Transaction Pairs 2
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TransactionPairs {
public static void main(String args[]) {
String url = "jdbc:mySubprotocol:myDataSource";
Connection con = null;
Statement stmt;
PreparedStatement updateSales;
PreparedStatement updateTotal;
String updateString = "update COFFEES "
+ "set SALES = ? where COF_NAME like ?";
String updateStatement = "update COFFEES "
+ "set TOTAL = TOTAL + ? where COF_NAME like ?";
String query = "select COF_NAME, SALES, TOTAL from COFFEES";
try {
Class.forName("myDriver.ClassName");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
con = DriverManager.getConnection(url, "myLogin", "myPassword");
updateSales = con.prepareStatement(updateString);
updateTotal = con.prepareStatement(updateStatement);
int[] salesForWeek = { 175, 150, 60, 155, 90 };
String[] coffees = { "Colombian", "French_Roast", "Espresso",
"Colombian_Decaf", "French_Roast_Decaf" };
int len = coffees.length;
con.setAutoCommit(false);
for (int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
updateTotal.setInt(1, salesForWeek[i]);
updateTotal.setString(2, coffees[i]);
updateTotal.executeUpdate();
con.rumit();
}
con.setAutoCommit(true);
updateSales.close();
updateTotal.close();
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String c = rs.getString("COF_NAME");
int s = rs.getInt("SALES");
int t = rs.getInt("TOTAL");
System.out.println(c + " " + s + " " + t);
}
stmt.close();
con.close();
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
if (con != null) {
try {
System.err.print("Transaction is being ");
System.err.println("rolled back");
con.rollback();
} catch (SQLException excep) {
System.err.print("SQLException: ");
System.err.println(excep.getMessage());
}
}
}
}
}
Using a database transaction with JDBC
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection connection = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection("jdbc:sqlserver://MYSERVER;databaseName=MYDATABASE",
"USERID", "PASSWORD");
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
statement.executeUpdate("UPDATE Table1 SET Value = 1 WHERE Name = "foo"");
statement.executeUpdate("UPDATE Table2 SET Value = 2 WHERE Name = "bar"");
connection.rumit();
} catch (SQLException ex) {
connection.rollback();
}
}
}