Dieses Programm incrementiert alle Zählerstände um 1.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MysqlCount {
static final String mysqlDriver = "com.mysql.jdbc.Driver";
static String dbConnect = "jdbc:mysql://localhost/inet";
static String user = "user";
static String pword = "password";
public static void main(String[] args) {
// load mysql driver
try {
Class.forName( mysqlDriver );
System.out.println("mysqlDriver " + mysqlDriver + " loaded");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// connect to database
Connection dbCon = null;
try {
dbCon = DriverManager.getConnection(dbConnect,user,pword);
System.out.println("connected to " + dbConnect);
dbCon.setAutoCommit( false );
} catch (SQLException e) {
e.printStackTrace();
}
if ( dbCon == null ) {
return;
}
// work with database
// increment all counters
Statement stmt = null;
PreparedStatement ustmt = null;
ResultSet rs = null;
String query = "SELECT url, count FROM counter";
String update = "UPDATE counter SET count = count + 1 WHERE url = ?";
try {
stmt = dbCon.createStatement();
System.out.println("statement created " + stmt);
ustmt = dbCon.prepareStatement(update);
rs = stmt.executeQuery( query );
while ( rs.next() ) {
String u = rs.getString(1);
int c = rs.getInt("count");
System.out.println("u = " + u + ", c = " +c);
ustmt.setString(1, u );
int rows = ustmt.executeUpdate();
System.out.println(""+ustmt + "\nrows = " + rows);
}
dbCon.commit();
rs.close();
if ( stmt != null ) {
stmt.close();
}
if ( ustmt != null ) {
ustmt.close();
}
} catch (SQLException e) {
try {
dbCon.rollback();
} catch (SQLException e1) {
}
e.printStackTrace();
}
try {
if ( dbCon != null ) {
dbCon.close();
System.out.println(dbConnect + " closed");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Ausgabe mit UPDATE:
java MysqlCount mysqlDriver com.mysql.jdbc.Driver loaded connected to jdbc:mysql://localhost/inet statement created com.mysql.jdbc.Statement@c2a132 u = /srv/www/htdocs/index.html, c = 36 com.mysql.jdbc.PreparedStatement@fa7e74: UPDATE counter SET count = count + 1 WHERE url = '/srv/www/htdocs/index.html' rows = 1 u = /home/heinz/htdocs/index.html, c = 281 com.mysql.jdbc.PreparedStatement@fa7e74: UPDATE counter SET count = count + 1 WHERE url = '/home/heinz/htdocs/index.html' rows = 1 ... jdbc:mysql://localhost/inet closed
© Universität Mannheim, Rechenzentrum, 2004.
Last modified: Sat Jun 5 15:25:40 CEST 2004