Thursday, 17 May 2007

JDBC

JDBC Introduction

The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.

JDBC helps you to write java applications that manage these three programming activities:

1. Connect to a data source, like a database
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to your query

The following simple code fragment gives a simple example of these three steps:

Connection con = DriverManager.getConnection
( "jdbc:myDriver:wombat", "myLogin","myPassword");

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}


This short code fragment instantiates a DriverManager object to connect to a database driver and log into the database, instantiates a Statement object that carries your SQL language query to the database; instantiates a ResultSet object that retrieves the results of your query, and executes a simple while loop, which retrieves and displays those results. It's that simple.

JDBC Product Components

JDBC includes four components:

1. The JDBC API —

The JDBC™ API provides programmatic access to relational data from the Java™ programming language. Using the JDBC API, applications can execute SQL statements, retrieve results, and propagate changes back to an underlying data source. The JDBC API can also interact with multiple data sources in a distributed, heterogeneous environment.

The JDBC API is part of the Java platform, which includes the Java™ Standard Edition (Java™ SE ) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.

2. JDBC Driver Manager —

The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple.

The Standard Extension packages javax.naming and javax.sql let you use a DataSource object registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a connection with a data source. You can use either connecting mechanism, but using a DataSource object is recommended whenever possible.

3. JDBC Test Suite —

The JDBC driver test suite helps you to determine that JDBC drivers will run your program. These tests are not comprehensive or exhaustive, but they do exercise many of the important features in the JDBC API.

4. JDBC-ODBC Bridge —

The Java Software bridge provides JDBC access via ODBC drivers. Note that you need to load ODBC binary code onto each client machine that uses this driver. As a result, the ODBC driver is most appropriate on a corporate network where client installations are not a major problem, or for application server code written in Java in a three-tier architecture.

This Trail uses the first two of these these four JDBC components to connect to a database and then build a java program that uses SQL commands to communicate with a test Relational Database. The last two components are used in specialized environments to test web applications, or to communicate with ODBC-aware DBMSs.
JDBC Architecture


Two-tier and Three-tier Processing Models

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.

The DBMS-proprietary protocol provides two-way communication between the client machine and the database server

In the two-tier model, a Java applet or application talks directly to the data source. This requires a JDBC driver that can communicate with the particular data source being accessed. A user's commands are delivered to the database or other data source, and the results of those statements are sent back to the user. The data source may be located on another machine to which the user is connected via a network. This is referred to as a client/server configuration, with the user's machine as the client, and the machine housing the data source as the server. The network can be an intranet, which, for example, connects employees within a corporation, or it can be the Internet.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the data source. The data source processes the commands and sends the results back to the middle tier, which then sends them to the user. MIS directors find the three-tier model very attractive because the middle tier makes it possible to maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide performance advantages.

Figure 2: Three-tier Architecture for Data Access.
The DBMS-proprietary protocol provides two-way communication between the database server and the server machine. HTTP, RMI, CORBA or other calls provide two way communication between the server machine and the client machine

Until recently, the middle tier has often been written in languages such as C or C++, which offer fast performance. However, with the introduction of optimizing compilers that translate Java bytecode into efficient machine-specific code and technologies such as Enterprise JavaBeans™, the Java platform is fast becoming the standard platform for middle-tier development. This is a big plus, making it possible to take advantage of Java's robustness, multithreading, and security features.

With enterprises increasingly using the Java programming language for writing server code, the JDBC API is being used more and more in the middle tier of a three-tier architecture. Some of the features that make JDBC a server technology are its support for connection pooling, distributed transactions, and disconnected rowsets. The JDBC API is also what allows access to a data source from a Java middle tier.

A Relational Database Overview

A database is a means of storing information in such a way that information can be retrieved from it. In simplest terms, a relational database is one that presents information in tables with rows and columns. A table is referred to as a relation in the sense that it is a collection of objects of the same type (rows). Data in a table can be related according to common keys or concepts, and the ability to retrieve related data from a table is the basis for the term relational database. A Database Management System (DBMS) handles the way data is stored, maintained, and retrieved. In the case of a relational database, a Relational Database Management System (RDBMS) performs these tasks. DBMS as used in this book is a general term that includes RDBMS.

Integrity Rules

Relational tables follow certain integrity rules to ensure that the data they contain stay accurate and are always accessible. First, the rows in a relational table should all be distinct. If there are duplicate rows, there can be problems resolving which of two possible selections is the correct one. For most DBMSs, the user can specify that duplicate rows are not allowed, and if that is done, the DBMS will prevent the addition of any rows that duplicate an existing row.

A second integrity rule of the traditional relational model is that column values must not be repeating groups or arrays. A third aspect of data integrity involves the concept of a null value. A database takes care of situations where data may not be available by using a null value to indicate that a value is missing. It does not equate to a blank or zero. A blank is considered equal to another blank, a zero is equal to another zero, but two null values are not considered equal.

When each row in a table is different, it is possible to use one or more columns to identify a particular row. This unique column or group of columns is called a primary key. Any column that is part of a primary key cannot be null; if it were, the primary key containing it would no longer be a complete identifier. This rule is referred to as entity integrity.

Table 1.2 illustrates some of these relational database concepts. It has five columns and six rows, with each row representing a different employee.

Table 1.2: Employees
Employee_Number First_name Last_Name Date_of_Birth Car_Number
10001 Axel Washington 28-Aug-43 5
10083 Arvid Sharma 24-Nov-54 null
10120 Jonas Ginsberg 01-Jan-69 null
10005 Florence Wojokowski 04-Jul-71 12
10099 Sean Washington 21-Sep-66 null
10035 Elizabeth Yamaguchi 24-Dec-59 null



The primary key for this table would generally be the employee number because each one is guaranteed to be different. (A number is also more efficient than a string for making comparisons.) It would also be possible to use First_Name and Last_Name because the combination of the two also identifies just one row in our sample database. Using the last name alone would not work because there are two employees with the last name of "Washington." In this particular case the first names are all different, so one could conceivably use that column as a primary key, but it is best to avoid using a column where duplicates could occur. If Elizabeth Taylor gets a job at this company and the primary key is First_Name, the RDBMS will not allow her name to be added (if it has been specified that no duplicates are permitted). Because there is already an Elizabeth in the table, adding a second one would make the primary key useless as a way of identifying just one row. Note that although using First_Name and Last_Name is a unique composite key for this example, it might not be unique in a larger database. Note also that Table 1.2 assumes that there can be only one car per employee.

SELECT Statements

SQL is a language designed to be used with relational databases. There is a set of basic SQL commands that is considered standard and is used by all RDBMSs. For example, all RDBMSs use the SELECT statement.

A SELECT statement, also called a query, is used to get information from a table. It specifies one or more column headings, one or more tables from which to select, and some criteria for selection. The RDBMS returns rows of the column entries that satisfy the stated requirements. A SELECT statement such as the following will fetch the first and last names of employees who have company cars:

SELECT First_Name, Last_Name
FROM Employees
WHERE Car_Number IS NOT NULL

The result set (the set of rows that satisfy the requirement of not having null in the Car_Number column) follows. The first name and last name are printed for each row that satisfies the requirement because the SELECT statement (the first line) specifies the columns First_Name and Last_Name. The FROM clause (the second line) gives the table from which the columns will be selected.

FIRST_NAME LAST_NAME
---------- -----------
Axel Washington
Florence Wojokowski

The following code produces a result set that includes the whole table because it asks for all of the columns in the table Employees with no restrictions (no WHERE clause). Note that SELECT * means "SELECT all columns."

SELECT *
FROM Employees

WHERE Clauses

The WHERE clause in a SELECT statement provides the criteria for selecting values. For example, in the following code fragment, values will be selected only if they occur in a row in which the column Last_Name begins with the string 'Washington'.

SELECT First_Name, Last_Name
FROM Employees
WHERE Last_Name LIKE 'Washington%'

The keyword LIKE is used to compare strings, and it offers the feature that patterns containing wildcards can be used. For example, in the code fragment above, there is a percent sign (%) at the end of 'Washington', which signifies that any value containing the string 'Washington' plus zero or more additional characters will satisfy this selection criterion. So 'Washington' or 'Washingtonian' would be matches, but 'Washing' would not be. The other wildcard used in LIKE clauses is an underbar (_), which stands for any one character. For example,

WHERE Last_Name LIKE 'Ba_man'

would match 'Batman', 'Barman', 'Badman', 'Balman', 'Bagman', 'Bamman', and so on.

The code fragment below has a WHERE clause that uses the equal sign (=) to compare numbers. It selects the first and last name of the employee who is assigned car 12.

SELECT First_Name, Last_Name
FROM Employees
WHERE Car_Number = 12

The next code fragment selects the first and last names of employees whose employee number is greater than 10005:

SELECT First_Name, Last_Name
FROM Employees
WHERE Employee_Number > 10005

WHERE clauses can get rather elaborate, with multiple conditions and, in some DBMSs, nested conditions. This overview will not cover complicated WHERE clauses, but the following code fragment has a WHERE clause with two conditions; this query selects the first and last names of employees whose employee number is less than 10100 and who do not have a company car.

SELECT First_Name, Last_Name
FROM Employees
WHERE Employee_Number < 10100 and Car_Number IS NULL

A special type of WHERE clause involves a join, which is explained in the next section.

Joins

A distinguishing feature of relational databases is that it is possible to get data from more than one table in what is called a join. Suppose that after retrieving the names of employees who have company cars, one wanted to find out who has which car, including the make, model, and year of car. This information is stored in another table, Cars, shown in Table 1.3.

Table 1.3. Cars
Car Number Make Model Year
5 Honda Civic DX 1996
12 Toyota Corolla 1999

There must be one column that appears in both tables in order to relate them to each other. This column, which must be the primary key in one table, is called the foreign key in the other table. In this case, the column that appears in two tables is Car_Number, which is the primary key for the table Cars and the foreign key in the table Employees. If the 1996 Honda Civic were wrecked and deleted from the Cars table, then Car_Number 5 would also have to be removed from the Employees table in order to maintain what is called referential integrity. Otherwise, the foreign key column (Car_Number) in Employees would contain an entry that did not refer to anything in Cars. A foreign key must either be null or equal to an existing primary key value of the table to which it refers. This is different from a primary key, which may not be null. There are several null values in the Car_Number column in the table Employees because it is possible for an employee not to have a company car.

The following code asks for the first and last names of employees who have company cars and for the make, model, and year of those cars. Note that the FROM clause lists both Employees and Cars because the requested data is contained in both tables. Using the table name and a dot (.) before the column name indicates which table contains the column.

SELECT Employees.First_Name, Employees.Last_Name, Cars.Make,
Cars.Model, Cars.Year
FROM Employees, Cars
WHERE Employees.Car_Number = Cars.Car_Number

This returns a result set that will look similar to the following:

FIRST_NAME LAST_NAME MAKE MODEL YEAR
----------- ------------ -------- --------- -------
Axel Washington Honda CivicDX 1996
Florence Wojokowski Toyota Corolla 1999


Common SQL Commands

SQL commands are divided into categories, the two main ones being Data Manipulation Language (DML) commands and Data Definition Language (DDL) commands. DML commands deal with data, either retrieving it or modifying it to keep it up-to-date. DDL commands create or change tables and other database objects such as views and indexes.

A list of the more common DML commands follows:

* SELECT — used to query and display data from a database. The SELECT statement specifies which columns to include in the result set. The vast majority of the SQL commands used in applications are SELECT statements.

* INSERT — adds new rows to a table. INSERT is used to populate a newly created table or to add a new row (or rows) to an already-existing table.

* DELETE — removes a specified row or set of rows from a table

* UPDATE — changes an existing value in a column or group of columns in a table

The more common DDL commands follow:

* CREATE TABLE — creates a table with the column names the user provides. The user also needs to specify a type for the data in each column. Data types vary from one RDBMS to another, so a user might need to use metadata to establish the data types used by a particular database. CREATE TABLE is normally used less often than the data manipulation commands because a table is created only once, whereas adding or deleting rows or changing individual values generally occurs more frequently.

* DROP TABLE — deletes all rows and removes the table definition from the database. A JDBC API implementation is required to support the DROP TABLE command as specified by SQL92, Transitional Level. However, support for the CASCADE and RESTRICT options of DROP TABLE is optional. In addition, the behavior of DROP TABLE is implementation-defined when there are views or integrity constraints defined that reference the table being dropped.

* ALTER TABLE — adds or removes a column from a table. It also adds or drops table constraints and alters column attributes

Result Sets and Cursors

The rows that satisfy the conditions of a query are called the result set. The number of rows returned in a result set can be zero, one, or many. A user can access the data in a result set one row at a time, and a cursor provides the means to do that. A cursor can be thought of as a pointer into a file that contains the rows of the result set, and that pointer has the ability to keep track of which row is currently being accessed. A cursor allows a user to process each row of a result set from top to bottom and consequently may be used for iterative processing. Most DBMSs create a cursor automatically when a result set is generated.

Earlier JDBC API versions added new capabilities for a result set's cursor, allowing it to move both forward and backward and also allowing it to move to a specified row or to a row whose position is relative to another row.

Transactions

When one user is accessing data in a database, another user may be accessing the same data at the same time. If, for instance, the first user is updating some columns in a table at the same time the second user is selecting columns from that same table, it is possible for the second user to get partly old data and partly updated data. For this reason, DBMSs use transactions to maintain data in a consistent state (data consistency) while allowing more than one user to access a database at the same time (data concurrency).

A transaction is a set of one or more SQL statements that make up a logical unit of work. A transaction ends with either a commit or a rollback, depending on whether there are any problems with data consistency or data concurrency. The commit statement makes permanent the changes resulting from the SQL statements in the transaction, and the rollback statement undoes all changes resulting from the SQL statements in the transaction.

A lock is a mechanism that prohibits two transactions from manipulating the same data at the same time. For example, a table lock prevents a table from being dropped if there is an uncommitted transaction on that table. In some DBMSs, a table lock also locks all of the rows in a table. A row lock prevents two transactions from modifying the same row, or it prevents one transaction from selecting a row while another transaction is still modifying it.

Stored Procedures

A stored procedure is a group of SQL statements that can be called by name. In other words, it is executable code, a mini-program, that performs a particular task that can be invoked the same way one can call a function or method. Traditionally, stored procedures have been written in a DBMS-specific programming language. The latest generation of database products allows stored procedures to be written using the Java programming language and the JDBC API. Stored procedures written in the Java programming language are bytecode portable between DBMSs. Once a stored procedure is written, it can be used and reused because a DBMS that supports stored procedures will, as its name implies, store it in the database.

The following code is an example of how to create a very simple stored procedure using the Java programming language. Note that the stored procedure is just a static Java method that contains normal JDBC code. It accepts two input parameters and uses them to change an employee's car number.

Do not worry if you do not understand the example at this point. The code example below is presented only to illustrate what a stored procedure looks like. You will learn how to write the code in this example in the tutorials that follow.


import java.sql.*;

public class UpdateCar {

public static void UpdateCarNum(int carNo, int empNo)
throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;

try {
con = DriverManager.getConnection("jdbc:default:connection");

pstmt = con.prepareStatement(
"UPDATE EMPLOYEES SET CAR_NUMBER = ? " +
"WHERE EMPLOYEE_NUMBER = ?");
pstmt.setInt(1, carNo);
pstmt.setInt(2, empNo);
pstmt.executeUpdate();
}
finally {
if (pstmt != null) pstmt.close();
}
}
}



Metadata

Databases store user data, and they also store information about the database itself. Most DBMSs have a set of system tables, which list tables in the database, column names in each table, primary keys, foreign keys, stored procedures, and so forth. Each DBMS has its own functions for getting information about table layouts and database features. JDBC provides the interface DatabaseMetaData, which a driver writer must implement so that its methods return information about the driver and/or DBMS for which the driver is written. For example, a large number of methods return whether or not the driver supports a particular functionality. This interface gives users and tools a standardized way to get metadata. In general, developers writing tools and drivers are the ones most likely to be concerned with metadata.



Establishing a Connection

First, you need to establish a connection with the DBMS you want to use. Typically, a JDBC™ application connects to a target data source using one of two mechanisms:

* DriverManager: This fully implemented class requires an application to load a specific driver, using a hardcoded URL. As part of its initialization, the DriverManager class attempts to load the driver classes referenced in the jdbc.drivers system property. This allows you to customize the JDBC Drivers used by your applications.

* DataSource: This interface is preferred over DriverManager because it allows details about the underlying data source to be transparent to your application. A DataSource object's properties are set so that it represents a particular data source.

Establishing a connection involves two steps: Loading the driver, and making the connection.

Loading the Driver

Loading the driver you want to use is very simple. It involves just one line of code in your program. To use the Java DB driver, add the following line of code:

Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

Your driver documentation provides the class name to use. In the example above, EmbeddedDriver is one of the drivers for Java DB.

Calling the Class.forName automatically creates an instance of a driver and registers it with the DriverManager, so you don't need to create an instance of the class. If you were to create your own instance, you would be creating an unnecessary duplicate, but it would do no harm.

After you have loaded a driver, it can make a connection with a DBMS.

Making the Connection

The second step in establishing a connection is to have the appropriate driver connect to the DBMS.

Using the DriverManager Class

The DriverManager class works with the Driver interface to manage the set of drivers available to a JDBC client. When the client requests a connection and provides a URL, the DriverManager is responsible for finding a driver that recognizes the URL and for using it to connect to the corresponding data source. Connection URLs have the following form:

jdbc:derby:[propertyList]

The dbName portion of the URL identifies a specific database. A database can be in one of many locations: in the current working directory, on the classpath, in a JAR file, in a specific Java DB database home directory, or in an absolute location on your file system.

If you are using a vendor-specific driver, such as Oracle, the documentation will tell you what subprotocol to use, that is, what to put after jdbc: in the JDBC URL. For example, if the driver developer has registered the name OracleDriver as the subprotocol, the first and second parts of the JDBC URL will be jdbc.driver.OracleDriver . The driver documentation will also give you guidelines for the rest of the JDBC URL. This last part of the JDBC URL supplies information for identifying the data source.

The getConnection method establishes a connection:

Connection conn = DriverManager.getConnection("jdbc:derby:COFFEES");

In place of " myLogin " you insert the name you use to log in to the DBMS; in place of " myPassword " you insert your password for the DBMS. So, if you log in to your DBMS with a login name of " Fernanda " and a password of " J8, " just these two lines of code will establish a connection:

String url = "jdbc:derby:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");


If one of the drivers you loaded recognizes the JDBC URL supplied to the method DriverManager.getConnection, that driver establishes a connection to the DBMS specified in the JDBC URL. The DriverManager class, true to its name, manages all of the details of establishing the connection for you behind the scenes. Unless you are writing a driver, you probably won't use any of the methods in the interface Driver, and the only DriverManager method you really need to know is DriverManager.getConnection

The connection returned by the method DriverManager.getConnection is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS. In the previous example, con is an open connection, and you use it in the examples that follow.

Using a DataSource Object for a connection

Using a DataSource object increases application portability by making it possible for an application to use a logical name for a data source instead of having to supply information specific to a particular driver. The following example shows how to use a DataSource to establish a connection:

You can configure a DataSource using a tool or manually. For example, Here is an example of a DataSource lookup:

InitialContext ic = new InitialContext()

DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");

Connection con = ds.getConnection();


DataSource implementations must provide getter and setter methods for each property they support. These properties typically are initialized when the DataSource object is deployed.


VendorDataSource vds = new VendorDataSource();
vds.setServerName("my_database_server");
String name = vds.getServerName();


JDBC-ODBC Bridge Driver

For normal use, you should obtain a commercial JDBC driver from a vendor such as your database vendor or your database middleware vendor. The JDBC-ODBC Bridge driver provided with JDBC is recommended only for development and testing, or when no other alternative is available

Setting Up Tables

For the following examples, you need to create a few tables in your database. The first table, COFFEES, contains the essential information about the coffees sold at The Coffee Break, including the coffee names, their prices, the number of pounds sold the current week, and the number of pounds sold to date. The table COFFEES, which is describe in more detail later, is shown here:

The Tables Used in the Example Database

The column storing the coffee name is COF_NAME, and it holds values with an SQL type of VARCHAR and a maximum length of 32 characters. Since the names are different for each type of coffee sold, the name uniquely identifies a particular coffee and serves as the primary key. The second column, named SUP_ID, holds a number identifying the coffee supplier; this number is of SQL type INTEGER. The third column, called PRICE, stores values with an SQL type of FLOAT because it needs to hold values with decimal points. (Note that money values would normally be stored in an SQL type DECIMAL or NUMERIC, but because of differences among DBMSs and to avoid incompatibility with older versions of JDBC, you are using the more standard type FLOAT for this tutorial.) The column named SALES stores values of SQL type INTEGER and indicates the number of pounds of coffee sold during the current week. The final column, TOTAL, contains an SQL INTEGER, which gives the total number of pounds of coffee sold to date.

SUPPLIERS, the second table in our database, gives information about each of the suppliers:

The tables COFFEES and SUPPLIERS both contain the column SUP_ID. These two tables can be used in SELECT statements to get data based on the information in both tables. The column SUP_ID is the primary key in the table SUPPLIERS, and as such, it uniquely identifies each of the coffee suppliers. In the table COFFEES, SUP_ID is called a foreign key. (You can think of a foreign key as being foreign in the sense that it is imported from another table.) Note that each SUP_ID number appears only once in the SUPPLIERS table; this is required for it to be a primary key. In the COFFEES table, where it is a foreign key, it is all right for there to be duplicate SUP_ID numbers because one supplier may sell many types of coffee. Later in this chapter, you see an example of how to use primary and foreign keys in a SELECT statement.

Creating Tables

You can create your tables in at least three ways:

* Using the database or IDE graphical interface

* Using ANT

* Using JDBC SQL written into an application


Creating a Tables Using the NetBeans IDE

Most database vendors provide a graphical user interface (GUI) that makes creating tables in your database easy. In addition, many IDEs, such as the NetBeans IDE, also provides an easy-to-use GUI for table creation.

For example, in the NetBeans™ 5.0 IDE, creating tables in the Java DB™ database is easy. After starting the database, either through the pull-down menu, or by right-clicking Databases, you add tables simply by right-clicking the Tables icon and selecting BBBCreate Table. You get a dialog box that looks like the one below:

Table creator in NetBeans

Fill in the dialog box fields and the NetBeans IDE creates the table. Adding or deleting rows is just as easy. Right-click the table to want to edit.

Creating Tables Using ANT

First, you can use a properties file to feed ANT, which has a simple sql target. Create a simple properties file, such as the one below:

# Database properties are in derby.properties
db.delimiter=;
db.root=${javaee.home}/derby
db.driver=org.apache.derby.jdbc.ClientDriver
db.datasource=org.apache.derby.jdbc.ClientDataSource
db.host=localhost
db.port=1527
db.sid=sun-appserv-samples
db.url=jdbc:derby://${db.host}:${db.port}/${db.sid};create=true;
db.user=APP
db.pwd=APP


Next, create a build.xml file that includes targets for compiling the Java code as well as a target similar to the following:

description="Create database tables and populate database.">
-
password="${db.password}" classpathref="db.classpath"
delimiter="${db.delimiter}" autocommit="false" onerror="abort">





The tutorial.sql file can contain the commands to create the tables and, possibly, populate the tables if need be, such as the example below:

create table COFFEES(cof_name varchar32, price int, sup_id int,
price float, sales int, total int);


The ';' matches the db.delimiter property.

NetBeans contains everything you need, including the Java DB and ANT. Download NetBeans.

Using SQL in an Application

Finally, you can create tables from within the application code itself. The following SQL statement creates the table named COFFEES. The entries within the outer pair of parentheses consist of the name of a column followed by a space and the SQL type to be stored in that column. A comma separates the entry for one column (consisting of column name and SQL type) from the next one. To be sure you are using the correct syntax, see your DBMS documentation. For the Java DB, read the current documentation.

This code does not end with a DBMS statement terminator, which can vary from DBMS to DBMS. For example, Oracle uses a semicolon (;) to indicate the end of a statement, and Sybase uses the word go. The driver you are using will automatically supply the appropriate statement terminator, and you will not need to include it in your JDBC code.
Note: In the CREATE TABLE statement, key words are printed in all capital letters, and each item is on a separate line. SQL does not require either; these conventions simply make statements easier to read. The standard in SQL is that keywords are not case sensitive, so, for example, the following SELECT statement can be written various ways. As an example, these two versions below are equivalent as far as SQL is concerned:

SELECT SUP_NAME, CITY
FROM Suppliers
WHERE SUP_NAME LIKE "Acme, Inc"
select SUP_Name, CITY from Suppliers where
SUP_NAME like "Acme, Inc;


Quoted material, however, is case sensitive: in the name " Washington," W must be capitalized, and the rest of the letters must be lowercase.

Requirements can vary from one DBMS to another when it comes to identifier names.

Retrieving Values from Result Sets

In the previous lesson, ResultSet was briefly mentioned. Now, you will learn the details of the ResultSet interface. The ResultSet interface provides methods for retrieving and manipulting the results of executed queries, and ResultSet objects can have different functionality and characteristics. These characteristics are result set type, result set concurrency, and cursor holdability. A table of data representing a database result set is usually generated by executing a statement that queries the database.

The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the cursor can be manipulated, and how concurrent changes made to the underlying data source are reflected by the ResultSet object.

The sensitivity of the ResultSet object is determined by one of three different ResultSet types:

1. TYPE_FORWARD_ONLY — The result set is not scrollable; its cursor moves forward only, from before the first row to after the last row. The rows contained in the result set depend on how the underlying database materializes the results. That is, it contains the rows that satisfy the query at either the time the query is executed or as the rows are retrieved.
2. TYPE_SCROLL_INSENSITIVE — The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.
3. TYPE_SCROLL_SENSITIVE — The result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.

Now, you'll see how to send the above SELECT statements from a program written in the Java™ programming language and how you get the results we showed.

JDBC™ returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. In addition, the Statement methods executeQuery and getResultSet both return a ResultSet object, as do various DatabaseMetaData methods. The following code demonstrates declaring the ResultSet object rs and assigning the results of our earlier query to it by using the executeQuery method.

Before you can take advantage of these features, however, you need to create a scrollable ResultSet object. The following line of code illustrates one way to create a scrollable ResultSet object:

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");


This code is similar to what you have used earlier, except that it adds two arguments to the createStatement method. The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int, the compiler will not complain if you switch the order.

Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

Using the ResultSet Methods

The variable srs, which is an instance of ResultSet, contains the rows of coffees and prices shown in the result set example above. In order to access the names and prices. A ResultSet object maintains a cursor, which points to its current row of data.

When a ResultSet object is first created, the cursor is positioned before the first row. To move the cursor, you can use the following methods:

* next() - moves the cursor forward one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row.
* previous() - moves the cursor backwards one row. Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row.
* first() - moves the cursor to the first row in the ResultSet object. Returns true if the cursor is now positioned on the first row and false if the ResultSet object does not contain any rows.
* last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now positioned on the last row and false if the ResultSet object does not contain any rows.
* beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet object does not contain any rows, this method has no effect.
* afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet object does not contain any rows, this method has no effect.
* relative(int rows) - moves the cursor relative to its current position.
* absolute(int row) - positions the cursor on the row-th row of the ResultSet object.

Once you have a scrollable ResultSet object, srs in the previous example, you can use it to move the cursor around in the result set. Since the cursor is initially positioned just above the first row of a ResultSet object, the first call to the method next moves the cursor to the first row and makes it the current row. Successive invocations of the method next move the cursor down one row at a time from top to bottom.

Using the getXXX Methods

The ResultSet interface declares getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Your application can retrieve values using either the index number of the column or the name of the column. The column index is usually more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.

Column names used as input to getter methods are case insensitive. When a getter method is called with a column name and several columns have the same name, the value of the first matching column will be returned. The column name option is designed to be used when column names are used in the SQL query that generated the result set. For columns that are NOT explicitly named in the query, it is best to use column numbers. If column names are used, the programmer should take care to guarantee that they uniquely refer to the intended columns, which can be assured with the SQL AS clause.

The getXXX method of the appropriate type retrieves the value in each column. For example, the first column in each row of srs is COF_NAME, which stores a value of SQL type VARCHAR. The method for retrieving a value of SQL type VARCHAR is getString. The second column in each row stores a value of SQL type FLOAT, and the method for retrieving values of that type is getFloat. The following code accesses the values stored in the current row of srs and prints a line with the name followed by three spaces and the price. Each time the method next is invoked, the next row becomes the current row, and the loop continues until there are no more rows in rs.

The method getString is invoked on the ResultSet object srs, so getString retrieves (gets) the value stored in the column COF_NAME in the current row of srs . The value that getString retrieves has been converted from an SQL VARCHAR to a String in the Java programming language, and it is assigned to the String object s.

Note that although the method getString is recommended for retrieving the SQL types CHAR and VARCHAR, it is possible to retrieve any of the basic SQL types with it. (You cannot, however, retrieve the new SQL3 datatypes with it. We will discuss SQL3 types later in this tutorial.) Getting all values with getString can be very useful, but it also has its limitations. For instance, if it is used to retrieve a numeric type, getString converts the numeric value to a Java String object, and the value has to be converted back to a numeric type before it can be operated on as a number. In cases where the value is treated as a string anyway, there is no drawback. Further, if you want an application to retrieve values of any standard SQL type other than SQL3 types, use the getString method.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(
"SELECT COF_NAME, PRICE FROM COFFEES");
while (srs.next()) {
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}

The output will look something like this:

Colombian 7.99
French_Roast 8.99
Espresso 9.99
Colombian_Decaf 8.99
French_Roast_Decaf 9.99

You can process all of the rows is srs going backward, but to do this, the cursor must start out located after the last row. You can move the cursor explicitly to the position after the last row with the method afterLast. Then the method previous() moves the cursor from the position after the last row to the last row, and then to the previous row with each iteration through the while loop. The loop ends when the cursor reaches the position before the first row, where the method previous() returns false .

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous()) {
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}

The printout will look similar to this:

French_Roast_Decaf 9.99
Colombian_Decaf 8.99
Espresso 9.99
French_Roast 8.99
Colombian 7.99

As you can see, the printout for each has the same values, but the rows are in the opposite order.

The situation is similar with the method getFloat except that it retrieves the value stored in the column PRICE, which is an SQL FLOAT, and converts it to a Java float before assigning it to the variable n.

JDBC offers two ways to identify the column from which a getXXX method gets a value. One way is to give the column name, as was done in the example above. The second way is to give the column index (number of the column), with 1 signifying the first column, 2 , the second, and so on. Using the column number instead of the column name looks like this:

String s = srs.getString(1);
float n = srs.getFloat(2);

The first line of code gets the value in the first column of the current row of rs (column COF_NAME), converts it to a Java String object, and assigns it to s. The second line of code gets the value stored in the second column of the current row of rs , converts it to a Java float, and assigns it to n. Note that the column number refers to the column number in the result set, not in the original table.

You can move the cursor to a particular row in a ResultSet object. The methods first, last, beforeFirst, and afterLast move the cursor to the row indicated in their names. The method absolute will move the cursor to the row number indicated in the argument passed to it. If the number is positive, the cursor moves the given number from the beginning, so calling absolute(1) puts the cursor on the first row. If the number is negative, the cursor moves the given number from the end, so calling absolute(-1) puts the cursor on the last row. The following line of code moves the cursor to the fourth row of srs:

srs.absolute(4);

If srs has 500 rows, the following line of code moves the cursor to row 497:


srs.absolute(-4);

Three methods move the cursor to a position relative to its current position. As you have seen, the method next moves the cursor forward one row, and the method previous moves the cursor backward one row. With the method relative, you can specify how many rows to move from the current row and also the direction in which to move. A positive number moves the cursor forward the given number of rows; a negative number moves the cursor backward the given number of rows. For example, in the following code fragment, the cursor moves to the fourth row, then to the first row, and finally to the third row:

srs.absolute(4); // cursor is on the fourth row
. . .
srs.relative(-3); // cursor is on the first row
. . .
srs.relative(2); // cursor is on the third row

The method getRow lets you check the number of the row where the cursor is positioned. For example, you can use getRow to verify the current position of the cursor in the previous example as follows:


srs.absolute(4);
int rowNum = srs.getRow(); // rowNum should be 4
srs.relative(-3);
int rowNum = srs.getRow(); // rowNum should be 1
srs.relative(2);
int rowNum = srs.getRow(); // rowNum should be 3

Four additional methods let you verify whether the cursor is at a particular position. The position is stated in their names: isFirst, isLast, isBeforeFirst, isAfterLast. These methods all return a boolean and can therefore be used in a conditional statement. For example, the following code fragment tests to see whether the cursor is after the last row before invoking the method previous in a while loop. If the method isAfterLast returns false, the cursor is not after the last row, so the method afterLast is invoked. This guarantees that the cursor will be after the last row and that using the method previous in the while loop will cover every row in srs.

if (srs.isAfterLast() == false) {
srs.afterLast();
}
while (srs.previous()) {
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}

In summary, JDBC allows you to use either the column name or the column number as the argument to a getXXX method. Using the column number is slightly more efficient, and there are some cases where the column number is required. In general, though, supplying the column name is essentially equivalent to supplying the column number.

JDBC allows a lot of latitude as far as which getXXX methods you can use to retrieve the different SQL types. For example, the method getInt can be used to retrieve any of the numeric or character types. The data it retrieves will be converted to an int; that is, if the SQL type is VARCHAR , JDBC will attempt to parse an integer out of the VARCHAR. The method getInt is recommended for retrieving only SQL INTEGER types, however, and it cannot be used for the SQL types BINARY, VARBINARY, LONGVARBINARY, DATE , TIME, or TIMESTAMP

Updating Tables

Next, you learn to update rows in a result set, using methods in the Java programming language rather than having to send an SQL command.

Updating a row in a ResultSet object is a two-phase process. First, the new value for each column being updated is set, and then the change is applied to the row. The row in the underlying data source is not updated until the second phase is completed.

The ResultSet interface contains two update methods for each JDBC™ type, one specifying the column to be updated as an index and one specifying the column name as it appears in the select list. Column names supplied to updater methods are case insensitive. If a select list contains the same column more than once, the first instance of the column will be updated.

First, you need to create a ResultSet object that is updatable. To do this, supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method, as you have seen in previous examples. The Statement object it creates produces an updatable ResultSet object each time it executes a query. The following code fragment illustrates creating the updatable ResultSet object uprs. Note that the code also makes uprs scrollable. An updatable ResultSet object does not necessarily have to be scrollable, but when you are making changes to a result set, you generally want to be able to move around in it. With a scrollable result set, you can move to rows you want to change, and if the type is TYPE_SCROLL_SENSITIVE, you can get the new value in a row after you have changed it.


Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

The ResultSet object uprs looks something like this:


COF_NAME PRICE
------------------ -----
Colombian 7.99
French_Roast 8.99
Espresso 9.99
Colombian_Decaf 8.99
French_Roast_Decaf 9.99


The method updateRow applies all column changes to the current row. The changes are not made to the row until updateRow has been called. You can use the cancelUpdates method to back out changes made to the row before the updateRow method is called.

Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
ResultSet srs = stmt.executeQuery("select COF_Name from COFFEES " +
"where price = 7.99");
srs.next();
srs.updateString("COF_NAME", "Foldgers");
srs.updateRow();

An update is the modification of a column value in the current row. Let's suppose that you want to raise the price of French Roast Decaf coffee to 10.99:

uprs.last();
uprs.updateFloat("PRICE", 10.99);

Update operations affect column values in the row where the cursor is positioned, so in the first line the ResultSet uprs calls the method last to move its cursor to the last row (the row where the column COF_NAME has the value FRENCH_ROAST_DECAF). Once the cursor is on the last row, all of the update methods you call will operate on that row until you move the cursor to another row. The second line changes the value in the PRICE column to 10.99 by calling the method updateFloat. This method is used because the column value we want to update is a float in the Java programming language.

The ResultSet. updateXXX methods take two parameters: the column to update and the new value to put in that column. As with the ResultSet.getXXX methods, the parameter designating the column may be either the column name or the column number. There is a different updateXXX method for updating each datatype ( updateString, updateBigDecimal, updateInt, and so on) just as there are different getXXX methods for retrieving different datatypes.

At this point, the price in uprs for French Roast Decaf will be 10.99, but the price in the table COFFEES in the database will still be 9.99. To make the update take effect in the database and not just the result set, we must call the ResultSet method updateRow. Here is what the code should look like to update both uprs and COFFEES :

uprs.last();
uprs.updateFloat("PRICE", 10.99f);
uprs.updateRow();

If you had moved the cursor to a different row before calling the method updateRow, the update would have been lost. If, on the other hand, you realized that the price should really have been 10.79 instead of 10.99, you could have cancelled the update to 10.99 by calling the method cancelRowUpdates. You have to invoke cancelRowUpdates before invoking the method updateRow; once updateRow is called, calling the method cancelRowUpdates does nothing. Note that cancelRowUpdates cancels all of the updates in a row, so if there are many invocations of the updateXXX methods on the same row, you cannot cancel just one of them. The following code fragment first cancels updating the price to 10.99 and then updates it to 10.79:

uprs.last();
uprs.updateFloat("PRICE", 10.99);
uprs.cancelRowUpdates();
uprs.updateFloat("PRICE", 10.79);
uprs.updateRow();

In this example, only one column value was updated, but you can call an appropriate updateXXX method for any or all of the column values in a single row. The concept to remember is that updates and related operations apply to the row where the cursor is positioned. Even if there are many calls to updateXXX methods, it takes only one call to the method updateRow to update the database with all of the changes made in the current row.

If you want to update the price for COLOMBIAN_DECAF as well, you have to move the cursor to the row containing that coffee. Because the row for COLOMBIAN_DECAF immediately precedes the row for FRENCH_ROAST_DECAF, you can call the method previous to position the cursor on the row for COLOMBIAN_DECAF. The following code fragment changes the price in that row to 9.79 in both the result set and the underlying table in the database:

uprs.previous();
uprs.updateFloat("PRICE", 9.79);
uprs.updateRow();

All cursor movements refer to rows in a ResultSet object, not rows in the underlying database. If a query selects five rows from a database table, there will be five rows in the result set, with the first row being row 1, the second row being row 2, and so on. Row 1 can also be identified as the first, and, in a result set with five rows, row 5 is the last.

The ordering of the rows in the result set has nothing at all to do with the order of the rows in the base table. In fact, the order of the rows in a database table is indeterminate. The DBMS keeps track of which rows were selected, and it makes updates to the proper rows, but they may be located anywhere in the table. When a row is inserted, for example, there is no way to know where in the table it has been inserted.

Using Prepared Statements

Sometimes it is more convenient to use a PreparedStatement object for sending SQL statements to the database. This special type of statement is derived from the more general class, Statement, that you already know.

If you want to execute a Statement object many times, it normally reduces execution time to use a PreparedStatement object instead.

The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.

Although PreparedStatement objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. Examples of this are in the following sections.

Creating a PreparedStatement Object

As with Statement objects, you create PreparedStatement objects with a Connection method. Using our open connection con from previous examples, you might write code such as the following to create a PreparedStatement object that takes two input parameters:

PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

The variable updateSales now contains the SQL statement, "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?", which has also, in most cases, been sent to the DBMS and been precompiled.

Supplying Values for PreparedStatement Parameters

You need to supply values to be used in place of the question mark placeholders (if there are any) before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the PreparedStatement class. If the value you want to substitute for a question mark is a Java int, you call the method setInt. If the value you want to substitute for a question mark is a Java String, you call the method setString, and so on. In general, there is a setXXX method for each primitive type declared in the Java programming language.

setXXX Using the PreparedStatement object updateSales from the previous example, the following line of code sets the first question mark placeholder to a Java int with a value of 75:

updateSales.setInt(1, 75);

setXXX The first argument given to a setXXX method indicates which question mark placeholder is to be set, and the second argument indicates the value to which it is to be set. The next example sets the second placeholder parameter to the string " Colombian":

updateSales.setString(2, "Colombian");


setXXX After these values have been set for its two input parameters, the SQL statement in updateSales is the equivalent to the SQL statement in the String object updateString that was used in the previous update example. Therefore, the following two code fragments accomplish the same thing:

Code Fragment 1:

String updateString = "UPDATE COFFEES SET SALES = 75 " +
"WHERE COF_NAME LIKE 'Colombian'";
stmt.executeUpdate(updateString);

Code Fragment 2:

PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate():

The method executeUpdate was used to execute both the Statement stmt and the PreparedStatement updateSales. Notice, however, that no argument is supplied to executeUpdate when it is used to execute updateSales. This is true because updateSales already contains the SQL statement to be executed.

Looking at these examples, you might wonder why you would choose to use a PreparedStatement object with parameters instead of just a simple statement, since the simple statement involves fewer steps. If you were going to update the SALES column only once or twice, then there would be no need to use an SQL statement with input parameters. If you will be updating often, on the other hand, it might be much easier to use a PreparedStatement object, especially in situations where you can use a for loop or while loop to set a parameter to a succession of values. You will see an example of this later in this section.

Once a parameter has been set with a value, it retains that value until it is reset to another value, or the method clearParameters is called. Using the PreparedStatement object updateSales, the following code fragment illustrates reusing a prepared statement after resetting the value of one of its parameters and leaving the other one the same:

updateSales.setInt(1, 100);
updateSales.setString(2, "French_Roast");
updateSales.executeUpdate();
// changes SALES column of French Roast row to 100
updateSales.setString(2, "Espresso");
updateSales.executeUpdate();
// changes SALES column of Espresso row to 100 (the first
// parameter stayed 100, and the second parameter was reset
// to "Espresso")


Using a Loop to Set Values

You can often make coding easier by using a for loop or a while loop to set values for input parameters.

The code fragment that follows demonstrates using a for loop to set values for parameters in the PreparedStatement object updateSales. The array salesForWeek holds the weekly sales amounts. These sales amounts correspond to the coffee names listed in the array coffees, so that the first amount in salesForWeek (175) applies to the first coffee name in coffees ("Colombian"), the second amount in salesForWeek (150) applies to the second coffee name in coffees ("French_Roast "), and so on. This code fragment demonstrates updating the SALES column for all the coffees in the table COFFEES:

PreparedStatement updateSales;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME like ?";
updateSales = con.prepareStatement(updateString);
int [] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian", "French_Roast", "Espresso",
"Colombian_Decaf", "French_Roast_Decaf"};
int len = coffees.length;
for(int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
}

When the proprietor wants to update the sales amounts for the next week, he can use this same code as a template. All he has to do is enter the new sales amounts in the proper order in the array salesForWeek. The coffee names in the array coffees remain constant, so they do not need to be changed. (In a real application, the values would probably be input from the user rather than from an initialized Java array.)

Return Values for the executeUpdate Method

Whereas executeQuery returns a ResultSet object containing the results of the query sent to the DBMS, the return value for executeUpdate is an int that indicates how many rows of a table were updated. For instance, the following code shows the return value of executeUpdate being assigned to the variable n:

updateSales.setInt(1, 50);
updateSales.setString(2, "Espresso");
int n = updateSales.executeUpdate();
// n = 1 because one row had a change in it

The table COFFEES was updated by having the value 50 replace the value in the column SALES in the row for Espresso. That update affected one row in the table, so n is equal to 1.

When the method executeUpdate is used to execute a DDL statement, such as in creating a table, it returns the int 0. Consequently, in the following code fragment, which executes the DDL statement used to create the table COFFEES, n is assigned a value of 0:

int n = executeUpdate(createTableCoffees); // n = 0

Note that when the return value for executeUpdate is 0, it can mean one of two things:

* the statement executed was an update statement that affected zero rows
*
* the statement executed was a DDL statement.


Using Joins

Sometimes you need to use two or more tables to get the data you want. For example, suppose the proprietor of The Coffee Break wants a list of the coffees he buys from Acme, Inc. This involves information in the COFFEES table as well as the yet-to-be-created SUPPLIERS table. This is a case where a join is needed. A join is a database operation that relates two or more tables by means of values that they share in common. In our example database, the tables COFFEES and SUPPLIERS both have the column SUP_ID, which can be used to join them.

Before we go any further, we need to create the table SUPPLIERS and populate it with values.

The code below creates the table SUPPLIERS:

String createSUPPLIERS = "create table SUPPLIERS " +
"(SUP_ID INTEGER, SUP_NAME VARCHAR(40), " +
"STREET VARCHAR(40), CITY VARCHAR(20), " +
"STATE CHAR(2), ZIP CHAR(5))";
stmt.executeUpdate(createSUPPLIERS);

The following code inserts rows for three suppliers into SUPPLIERS:

stmt.executeUpdate("insert into SUPPLIERS values (101, " +
"'Acme, Inc.', '99 Market Street', 'Groundsville', " + "'CA', '95199'");
stmt.executeUpdate("Insert into SUPPLIERS values (49," +
"'Superior Coffee', '1 Party Place', 'Mendocino', 'CA', " + "'95460'");
stmt.executeUpdate("Insert into SUPPLIERS values (150, " +
"'The High Ground', '100 Coffee Lane', 'Meadows', 'CA', " + "'93966'");

The following code selects the whole table and lets us see what the table SUPPLIERS looks like:

ResultSet rs = stmt.executeQuery("select * from SUPPLIERS");

Now that we have the tables COFFEES and SUPPLIERS, we can proceed with the scenario where the owner wants to get a list of the coffees he buys from a particular supplier. The names of the suppliers are in the table SUPPLIERS, and the names of the coffees are in the table COFFEES. Since both tables have the column SUP_ID, this column can be used in a join. It follows that you need some way to distinguish which SUP_ID column you are referring to. This is done by preceding the column name with the table name, as in "COFFEES.SUP_ID" to indicate that you mean the column SUP_ID in the table COFFEES. The following code, in which stmt is a Statement object, selects the coffees bought from Acme, Inc.:

String query = "
SELECT COFFEES.COF_NAME " +
"FROM COFFEES, SUPPLIERS " +
"WHERE SUPPLIERS.SUP_NAME LIKE 'Acme, Inc.' " +
"and SUPPLIERS.SUP_ID = COFFEES.SUP_ID";

ResultSet rs = stmt.executeQuery(query);
System.out.println("Coffees bought from Acme, Inc.: ");
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
System.out.println(" " + coffeeName);
}

This will produce the following output:

Coffees bought from Acme, Inc.:
Colombian
Colombian_Decaf


Using Transactions

There are times when you do not want one statement to take effect unless another one completes. For example, when the proprietor of The Coffee Break updates the amount of coffee sold each week, he will also want to update the total amount sold to date. However, he will not want to update one without updating the other; otherwise, the data will be inconsistent. The way to be sure that either both actions occur or neither action occurs is to use a transaction. A transaction is a set of one or more statements that are executed together as a unit, so either all of the statements are executed, or none of the statements is executed.

Disabling Auto-commit Mode

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and is automatically committed right after it is executed. (To be more precise, the default is for an SQL statement to be committed when it is completed, not when it is executed. A statement is completed when all of its result sets and update counts have been retrieved. In almost all cases, however, a statement is completed, and therefore committed, right after it is executed.)

The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode. This is demonstrated in the following line of code, where con is an active connection:

con.setAutoCommit(false);

Committing a Transaction

Once auto-commit mode is disabled, no SQL statements are committed until you call the method commit explicitly. All statements executed after the previous call to the method commit are included in the current transaction and committed together as a unit. The following code, in which con is an active connection, illustrates a transaction:

con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement(
"UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

In this example, auto-commit mode is disabled for the connection con, which means that the two prepared statements updateSales and updateTotal are committed together when the method commit is called. Whenever the commit method is called (either automatically when auto-commit mode is enabled or explicitly when it is disabled), all changes resulting from statements in the transaction are made permanent. In this case, that means that the SALES and TOTAL columns for Colombian coffee have been changed to 50 (if TOTAL had been 0 previously) and will retain this value until they are changed with another update statement. TransactionPairs.java illustrates a similar kind of transaction but uses a for loop to supply values to the setXXX methods for updateSales and updateTotal.

The final line of the previous example enables auto-commit mode, which means that each statement is once again committed automatically when it is completed. Then, you are back to the default state where you do not have to call the method commit yourself. It is advisable to disable auto-commit mode only while you want to be in transaction mode. This way, you avoid holding database locks for multiple statements, which increases the likelihood of conflicts with other users.

Using Transactions to Preserve Data Integrity

In addition to grouping statements together for execution as a unit, transactions can help to preserve the integrity of the data in a table. For instance, suppose that an employee was supposed to enter new coffee prices in the table COFFEES but delayed doing it for a few days. In the meantime, prices rose, and today the owner is in the process of entering the higher prices. The employee finally gets around to entering the now outdated prices at the same time that the owner is trying to update the table. After inserting the outdated prices, the employee realizes that they are no longer valid and calls the Connection method rollback to undo their effects. (The method rollback aborts a transaction and restores values to what they were before the attempted update.) At the same time, the owner is executing a SELECT statement and printing out the new prices. In this situation, it is possible that the owner will print a price that was later rolled back to its previous value, making the printed price incorrect.

This kind of situation can be avoided by using transactions, providing some level of protection against conflicts that arise when two users access data at the same time.

To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each statement is a transaction, locks are held for only one statement.) Once a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)

How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.

One example of a transaction isolation level is TRANSACTION_READ_COMMITTED, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set to TRANSACTION_READ_COMMITTED, the DBMS does not allow dirty reads to occur. The interface Connection includes five values which represent the transaction isolation levels you can use in JDBC.

Normally, you do not need to do anything about the transaction isolation level; you can just use the default one for your DBMS. JDBC allows you to find out what transaction isolation level your DBMS is set to (using the Connection method getTransactionIsolation) and also allows you to set it to another level (using the Connection method setTransactionIsolation). Keep in mind, however, that even though JDBC allows you to set a transaction isolation level, doing so has no effect unless the driver and DBMS you are using support it.

Setting and Rolling Back to a Savepoint

The JDBC 3.0 API adds the method Connection.setSavepoint, which sets a savepoint within the current transaction. The Connection.rollback method has been overloaded to take a savepoint argument.

The example below inserts a row into a table, sets the savepoint svpt1, and then inserts a second row. When the transaction is later rolled back to svpt1, the second insertion is undone, but the first insertion remains intact. In other words, when the transaction is committed, only the row containing ?FIRST? will be added to TAB1:

Statement stmt = conn.createStatement();
int rows = stmt.executeUpdate("INSERT INTO TAB1 (COL1) VALUES " +
"(?FIRST?)");
// set savepoint
Savepoint svpt1 = conn.setSavepoint("SAVEPOINT_1");
rows = stmt.executeUpdate("INSERT INTO TAB1 (COL1) " +
"VALUES (?SECOND?)");
...
conn.rollback(svpt1);
...
conn.commit();

Releasing a Savepoint

The method Connection.releaseSavepoint takes a Savepoint object as a parameter and removes it from the current transaction.

Once a savepoint has been released, attempting to reference it in a rollback operation causes an SQLException to be thrown. Any savepoints that have been created in a transaction are automatically released and become invalid when the transaction is committed, or when the entire transaction is rolled back. Rolling a transaction back to a savepoint automatically releases and makes invalid any other savepoints that were created after the savepoint in question.

When to Call the Method rollback

As mentioned earlier, calling the method rollback aborts a transaction and returns any values that were modified to their previous values. If you are trying to execute one or more statements in a transaction and get an SQLException, you should call the method rollback to abort the transaction and start the transaction all over again. That is the only way to be sure of what has been committed and what has not been committed. Catching an SQLException tells you that something is wrong, but it does not tell you what was or was not committed. Since you cannot count on the fact that nothing was committed, calling the method rollback is the only way to be sure.

TransactionPairs.java demonstrates a transaction and includes a catch block that invokes the method rollback. In this particular situation, it is not really necessary to call rollback, and we do it mainly to illustrate how it is done. If the application continued and used the results of the transaction, however, it would be necessary to include a call to rollback in the catch block in order to protect against using possibly incorrect data.

Stored Procedures

A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.

Stored procedures are supported by most DBMSs, but there is a fair amount of variation in their syntax and capabilities. For this reason, we will show you a simple example of what a stored procedure looks like and how it is invoked from JDBC, but this sample is not intended to be run.

SQL Statements for Creating a Stored Procedure

A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and they are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.

Note: Stored procedures are supported by most DBMSs, but there is a fair amount of variation in their syntax and capabilities. For this reason, this simple example of what a stored procedure looks like and how it is invoked from JDBC is not intended to be run.

This simple stored procedure has no parameters. Even though most stored procedures do something more complex than this example, it serves to illustrate some basic points about them. As previously stated, the syntax for defining a stored procedure is different for each DBMS. For example, some use begin . . . end , or other keywords to indicate the beginning and ending of the procedure definition. In some DBMSs, the following SQL statement creates a stored procedure:

create procedure SHOW_SUPPLIERS
as
select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME
from SUPPLIERS, COFFEES
where SUPPLIERS.SUP_ID = COFFEES.SUP_ID
order by SUP_NAME

The following code puts the SQL statement into a string and assigns it to the variable createProcedure, which we will use later:

String createProcedure = "create procedure SHOW_SUPPLIERS " +
"as " +
"select SUPPLIERS.SUP_NAME, COFFEES.COF_NAME " +
"from SUPPLIERS, COFFEES " +
"where SUPPLIERS.SUP_ID = COFFEES.SUP_ID " +
"order by SUP_NAME";

The following code fragment uses the Connection object con to create a Statement object, which is used to send the SQL statement creating the stored procedure to the database:

Statement stmt = con.createStatement();
stmt.executeUpdate(createProcedure);

The procedure SHOW_SUPPLIERS is compiled and stored in the database as a database object that can be called, similar to the way you would call a method.

Calling a Stored Procedure from JDBC

JDBC allows you to call a database stored procedure from an application written in the Java programming language. The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A callableStatement object contains a call to a stored procedure; it does not contain the stored procedure itself. The first line of code below creates a call to the stored procedure SHOW_SUPPLIERS using the connection con. The part that is enclosed in curly braces is the escape syntax for stored procedures. When the driver encounters "{call SHOW_SUPPLIERS}", it will translate this escape syntax into the native SQL used by the database to call the stored procedure named SHOW_SUPPLIERS.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

The ResultSet rs will be similar to the following:

SUP_NAME COF_NAME
---------------- -----------------------
Acme, Inc. Colombian
Acme, Inc. Colombian_Decaf
Superior Coffee French_Roast
Superior Coffee French_Roast_Decaf
The High Ground Espresso

Note that the method used to execute cs is executeQuery because cs calls a stored procedure that contains one query and thus produces one result set. If the procedure had contained one update or one DDL statement, the method executeUpdate would have been the one to use. It is sometimes the case, however, that a stored procedure contains more than one SQL statement, in which case it will produce more than one result set, more than one update count, or some combination of result sets and update counts. In this case, where there are multiple results, the method execute should be used to execute the CallableStatement .

The class CallableStatement is a subclass of PreparedStatement, so a CallableStatement object can take input parameters just as a PreparedStatement object can. In addition, a CallableStatement object can take output parameters, or parameters that are for both input and output. INOUT parameters and the method execute are used rarely.

Creating Complete JDBC Applications

Up to this point, you have seen only code fragments. Now you will see some samples.

The first sample code creates the table COFFEES; the second one inserts values into the table and prints the results of a query. The third application creates the table SUPPLIERS, and the fourth populates it with values. After you have run this code, you can try a query that is a join between the tables COFFEES and SUPPLIERS, as in the fifth code example. The sixth code sample is an application that demonstrates a transaction and also shows how to set placeholder parameters in a PreparedStatement object using a for loop.

Because they are complete applications, they include some elements of the Java programming language we have not shown before in the code fragments. We will explain these elements briefly here.

Putting Code in a Class Definition

In the Java™ programming language, any code you want to execute must be inside a class definition. You type the class definition in a file and give the file the name of the class with .java appended to it. So if you have a class named MySQLStatement, its definition should be in a file named MySQLStatement.java.

Importing Classes to Make Them Visible

The first thing to do is to import the packages or classes you will be using in the new class. The classes in our examples all use the java.sql package (the JDBC™ API), which becomes available when the following line of code precedes the class definition:

import java.sql.*;

The star ( * ) indicates that all of the classes in the package java.sql are to be imported. Importing a class makes it visible and means that you do not have to write out the fully qualified name when you use a method or field from that class. If you do not include " import java.sql.*; " in your code, you will have to write " java.sql. " plus the class name in front of all the JDBC fields or methods you use every time you use them. Note that you can import individual classes selectively rather than a whole package. Java does not require that you import classes or packages, but doing so makes writing code a lot more convenient.

Any lines importing classes appear at the top of all the code samples, as they must if they are going to make the imported classes visible to the class being defined. The actual class definition follows any lines that import classes.

Using the main Method

If a class is to be executed, it must contain a static public main method. This method comes right after the line declaring the class and invokes the other methods in the class. The keyword static indicates that this method operates on a class level rather than on individual instances of a class. The keyword public means that members of any class can access this method. Since we are not just defining classes to be used by other classes but instead want to run them, the example applications in this chapter all include a main method.

Using try and catch Blocks

Something else all the sample applications include is try and catch blocks. These are the Java programming language's mechanism for handling exceptions. Java requires that when a method throws an exception, there be some mechanism to handle it. Generally a catch block will catch the exception and specify what happens (which you may choose to be nothing). In the sample code, we use two try blocks and two catch blocks. The first try block contains the method Class.forName, from the java.lang package. This method throws a ClassNotFoundException, so the catch block immediately following it deals with that exception. The second try block contains JDBC methods, which all throw SQLExceptions, so one catch block at the end of the application can handle all of the rest of the exceptions that might be thrown because they will all be SQLException objects.

Retrieving Exceptions

JDBC lets you see the warnings and exceptions generated by your DBMS and by the Java compiler. To see exceptions, you can have a catch block print them out. For example, the following two catch blocks from the sample code print out a message explaining the exception:

try {
// Code that could generate an exception goes here.
// If an exception is generated, the catch block below
// will print out information about it.
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}

try {
Class.forName("myDriverClassName");
} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}

If you were to run CreateCOFFEES.java twice, you would get an error message similar to this:

SQLException: There is already an object named 'COFFEES'
in the database.
Severity 16, State 1, Line 1

This example illustrates printing out the message component of an SQLException object, which is sufficient for most situations.

There are actually three components, however, and to be complete, you can print them all out. The following code fragment shows a catch block that is complete in two ways. First, it prints out all three parts of an SQLException object: the message (a string that describes the error), the SQL state (a string identifying the error according to the X/Open SQLState conventions), and the vendor error code (a number that is the driver vendor's error code number). The SQLException object ex is caught, and its three components are accessed with the methods getMessage , getSQLState , and getErrorCode .

The second way the following catch block is complete is that it gets all of the exceptions that might have been thrown. If there is a second exception, it will be chained to ex, so ex.getNextException is called to see if there is another exception. If there is, the while loop continues and prints out the next exception's message, SQLState, and vendor error code. This continues until there are no more exceptions.

try {
// Code that could generate an exception goes here.
// If an exception is generated, the catch block below
// will print out information about it.
} catch(SQLException ex) {
System.out.println("\n--- SQLException caught ---\n");
while (ex != null) {
System.out.println("Message: "
+ ex.getMessage ());
System.out.println("SQLState: "
+ ex.getSQLState ());
System.out.println("ErrorCode: "
+ ex.getErrorCode ());
ex = ex.getNextException();
System.out.println("");
}
}

If you were to substitute the catch block above into the code and run it after the table COFFEES had already been created, you would get the following printout:

--- SQLException caught ---
Message: There is already an object named 'COFFEES' in the database.
Severity 16, State 1, Line 1
SQLState: 42501
ErrorCode: 2714

The vendor error code is specific to each driver, so you need to check your driver documentation for a list of error codes and what they mean.

Retrieving Warnings

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. For example, a warning might let you know that a privilege you attempted to revoke was not revoked. Or a warning might tell you that an error occurred during a requested disconnection.

A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object. If getWarnings returns a warning, you can call the SQLWarning method getNextWarning on it to get any additional warnings. Executing a statement automatically clears the warnings from a previous statement, so they do not build up. This means, however, that if you want to retrieve warnings reported on a statement, you must do so before you execute another statement.

The following code fragment illustrates how to get complete information about any warnings reported on the Statement object stmt and also on the ResultSet object rs :

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select COF_NAME from COFFEES");
while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
System.out.println("Coffees available at the Coffee Break: ");
System.out.println(" " + coffeeName);
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
System.out.println("\n---Warning---\n");
while (warning != null) {
System.out.println("Message: "
+ warning.getMessage());
System.out.println("SQLState: "
+ warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
System.out.println("");
warning = warning.getNextWarning();
}
}
SQLWarning warn = rs.getWarnings();
if (warn != null) {
System.out.println("\n---Warning---\n");
while (warn != null) {
System.out.println("Message: "
+ warn.getMessage());
System.out.println("SQLState: "
+ warn.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warn.getErrorCode());
System.out.println("");
warn = warn.getNextWarning();
}
}
}


Warnings are actually rather uncommon. Of those that are reported, by far the most common warning is a DataTruncation warning, a subclass of SQLWarning. All DataTruncation objects have an SQLState of 01004, indicating that there was a problem with reading or writing data. DataTruncation methods let you find out in which column or parameter data was truncated, whether the truncation was on a read or write operation, how many bytes should have been transferred, and how many bytes were actually transferred.

Running the Sample Applications

You are now ready to actually try out some sample code. The directory book.html contains complete, runnable applications that illustrate concepts presented in this chapter and the next. You can download this sample code from the JDBC web site located at:

JDBC Technology Code Samples


Before you can run one of these applications, you will need to edit the file by substituting the appropriate information for the following variables:

url
the JDBC URL; parts one and two are supplied by your driver, and the third part specifies your data source
myLogin
your login name or user name
myPassword
your password for the DBMS
myDriver.ClassName
the class name supplied with your driver

The first example application is the class CreateCoffees , which is in a file named CreateCoffees.java . Below are instructions for running CreateCoffees.java on the three major platforms.

The first line in the instructions below compiles the code in the file CreateCoffees.java . If the compilation is successful, it will produce a file named CreateCoffees.class , which contains the bytecodes translated from the file CreateCoffees.java . These bytecodes will be interpreted by the Java Virtual Machine, which is what makes it possible for Java code to run on any machine with a Java Virtual Machine installed on it.

The second line of code is what actually makes the code run. Note that you use the name of the class, CreateCoffees , not the name of the file, CreateCoffees.class .

UNIX

javac CreateCoffees.java
java CreateCoffees

Windows 95/NT

javac CreateCoffees.java
java CreateCoffees




Creating an Applet from an Application

Suppose that the owner of The Coffee Break wants to display his current coffee prices in an applet on his web page. He can be sure of always displaying the most current price by having the applet get the price directly from his database.

In order to do this, he needs to create two files of code, one with applet code, and one with HTML code. The applet code contains the JDBC code that would appear in a regular application plus additional code for running the applet and displaying the results of the database query. In our example, the applet code is in the file OutputApplet.java. To display our applet in an HTML page, the file OutputApplet.html tells the browser what to display and where to display it.

The rest of this section will tell you about various elements found in applet code that are not present in standalone application code. Some of these elements involve advanced aspects of the Java programming language. We will give you some rationale and some basic explanation, but explaining them fully is beyond the scope of this tutorial. For purposes of this sample applet, you only need to grasp the general idea, so don't worry if you don't understand everything. You can use the applet code as a template, substituting your own queries for the one in the applet.

Writing Applet Code

To begin with, applets will import classes not used by standalone applications. Our applet imports two classes that are special to applets: the class Applet , which is part of the java.applet package, and the class Graphics , which is part of the java.awt package. This applet also imports the general-purpose class java.util.Vector so that we have access to an array-like container whose size can be modified. This code uses Vector objects to store query results so that they can be displayed later.

All applets extend the Applet class; that is, they are subclasses of Applet . Therefore, every applet definition must contain the words extends Applet , as shown here:

public class MyAppletName extends Applet {
. . .
}

In our applet example, OutputApplet, this line also includes the words implements Runnable , so it looks like this:

public class OutputApplet extends Applet implements Runnable {
. . .
}

Runnable is an interface that makes it possible to run more than one thread at a time. A thread is a sequential flow of control, and it is possible for a program to be multithreaded, that is, to have many threads doing different things concurrently. The class OutputApplet implements the interface Runnable by defining the method run , the only method in Runnable . In our example the run method contains the JDBC code for opening a connection, executing a query, and getting the results from the result set. Since database connections can be slow, and can sometimes take several seconds, it is generally a good idea to structure an applet so that it can handle the database work in a separate thread.

Similar to a standalone application, which must have a main method, an applet must implement at least one init , start , or paint method. Our example applet defines a start method and a paint method. Every time start is invoked, it creates a new thread (named worker ) to re-evaluate the database query. Every time paint is invoked, it displays either the query results or a string describing the current status of the applet.

As stated previously, the run method defined in OutputApplet contains the JDBC code. When the thread worker invokes the method start , the run method is called automatically, and it executes the JDBC code in the thread worker . The code in run is very similar to the code you have seen in our other sample code with three exceptions. First, it uses the class Vector to store the results of the query. Second, it does not print out the results but rather adds them to the Vector results for display later. Third, it likewise does not print out exceptions and instead records error messages for later display.

Applets have various ways of drawing, or displaying, their content. This applet, a very simple one that has only text, uses the method drawString (part of the Graphics class) to display its text. The method drawString takes three arguments: (1) the string to be displayed, (2) the x coordinate, indicating the horizontal starting point for displaying the string, and (3) the y coordinate, indicating the vertical starting point for displaying the string (which is below the text).

The method paint is what actually displays something on the screen, and in OutputApplet.java , it is defined to contain calls to the method drawString . The main thing drawString displays is the contents of the Vector results (the stored query results). When there are no query results to display, drawString will display the current contents of the String message . This string will be "Initializing" to begin with. It gets set to "Connecting to database" when the method start is called, and the method setError sets it to an error message when an exception is caught. Thus, if the database connection takes much time, the person viewing this applet will see the message "Connecting to database" because that will be the contents of message at that time. (The method paint is called by AWT when it wants the applet to display its current state on the screen.)

The last two methods defined in the class OutputApplet, setError and setResults are private, which means that they can be used only by OutputApplet. These methods both invoke the method repaint , which clears the screen and calls paint . So if setResults calls repaint , the query results will be displayed, and if setError calls repaint , an error message will be displayed.

A final point to be made is that all the methods defined in OutputApplet except run are synchronized . The keyword synchronized indicates that while a method is accessing an object, other synchronized methods are blocked from accessing that object. The method run is not declared synchronized so that the applet can still paint itself on the screen while the database connection is in progress. If the database access methods were synchronized , they would prevent the applet from being repainted while they are executing, and that could result in delays with no accompanying status message.

To summarize, in an applet, it is good programming practice to do some things you would not need to do in a standalone application:

1. Put your JDBC code in a separate thread
2. Display status messages on the screen during any delays, such as when a database connection is taking a long time
3. Display error messages on the screen instead of printing them to System.out or System.err .

Running an Applet

Before running our sample applet, you need to compile the file OutputApplet.java . This creates the file OutputApplet.class , which is referenced by the file OutputApplet.html.

The easiest way to run an applet is to use the appletviewer, which is included as part of the JDK. Simply follow the instructions below for your platform to compile and run OutputApplet.java :

UNIX

javac OutputApplet.java
appletviewer OutputApplet.html

Windows 95/NT

javac OutputApplet.java
appletviewer OutputApplet.html

Applets loaded over the network are subject to various security restrictions. Although this can seem bothersome at times, it is absolutely necessary for network security, and security is one of the major advantages of using the Java programming language. An applet cannot make network connections except to the host it came from unless the browser allows it. Whether one is able to treat locally installed applets as "trusted" also depends on the security restrictions imposed by the browser. An applet cannot ordinarily read or write files on the host that is executing it, and it cannot load libraries or define native methods.

Applets can usually make network connections to the host they came from, so they can work very well on intranets.

The JDBC-ODBC Bridge driver is a somewhat special case. It can be used quite successfully for intranet access, but it requires that ODBC, the bridge, the bridge native library, and JDBC be installed on every client. With this configuration, intranet access works from Java applications and from trusted applets. However, since the bridge requires special client configuration, it is not practical to run applets on the Internet with the JDBC-ODBC Bridge driver. Note that this is a limitation of the JDBC-ODBC Bridge, not of JDBC. With a pure Java JDBC driver, you do not need any special configuration to run applets on the Internet.
















from java lecture

Connecting to a Database
We have a network which supports a communication protocol e.g. TCP/IP
The Database listens to a port (a 2 way thing)
The Database will define some higher level protocol for queries (SQL) and returned results (tables)
we DON’T WANT to have to code at this level! Hence JDBC (it is all done for us again!)

ODBC Came First
Slow

JDBC is A Java API for database communication
Connect to relational databases
Send SQL commands
Process results

About the Database
host = “unnc-cslinux”;
database = “your username”;
port = 5432;
user = “your username”;
password = “I will email you";

Register the Driver
import java.sql.*; // You NEED this!
…
Connection con;
try {
Class.forName(“org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
System.out.println(ex.getErrorCode());
}

Connect to Database
Connection con;
con = DriverManager.getConnection(url, username, passwd);
Where:
String url = “jdbc:postgresql://unnc-cslinux:5432/yourusername”;

Create and Execute a Statement
Statement st = con.createStatement();
String qry = “SELECT ...”;
ResultSet rs = st.executeQuery(qry);

String qry = “INSERT ...”;
st.executeUpdate(qry);


JDBC Statements
Getting the data returned
String code = rs.getString(“code");
Needs to be in a try block
Of course other methods are:
getInt();
getDouble();


Navigating the ResultSet

while(rs.next()) {
… process a row
}

Important point…

con.close();


How to connect in Java
DBconnect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
pConnection=DriverManager.getConnection("jdbc:odbc:mydb.mdb","","");
pStatement = pConnection.createStatement();
}
catch(Exception e) { e.getMessage(); // print this out
}
}





from DBS lecture:

Basic steps when using JDBC
Register a database driver
Open a connection
Pass some queries to the database
Process the results as needed
Close the connection
Deal with any errors

// Declaration of any database objects
try {
// Some database code
} catch (Exception e) {
// Error reporting etc.
} finally {
// Make sure all database objects are
// closed and cleaned up
}

Applets and Graphics

CHAPTER 36—Applets
An applet usually is used as part of a Web page. The applet is responsible for the graphical components and user interaction in a rectangular section of the Web browser's screen. Applets are typically used for user interaction with the Web page.

An applet is an object that is used by another program, typically a Web browser. The Web browser is the application program and (at least conceptually) holds the main() method. The applet part of a Web page provides services (methods) to the browser when the browser asks for them.

To access these definitions, your program should import javax.applet.JApplet and java.awt.*.

drawString( String str, int x, int y)
str — a String to place into the drawing area
x — horizontal distance in pixels from the left edge
y — vertical distance in pixels from the top edge

Distance is measured in pixels. A pixel is one of the graph paper squares that the video screen has been (conceptually) divided into. If your monitor is set to a resolution of 800 by 600, then the whole screen is divided into 800 horizontal squares and 600 vertical squares. An applet will usually cover only part of that area, perhaps an area 300 horizontal by 150 vertical. It is the responsibility of the graphics card and its driver to implement this idea of graph paper on the actual electronics of you computer system.

An applet does not have a main() method and so cannot be started as an application.

appletviewer displays only the applet part of an HTML file. The other parts (if any) are omitted.
Appletviewer is run from the command prompt window. If javac and java have been working, then the following should work:

C:\>appletviewer AnotherHello.html

mark the START of a "html" file. These should be the FIRST characters in the file.
mark the END of a "html" file. These should be the LAST characters in the file.
mark the start of the head of the file. The head of the file contains descriptions and declarations that are not supposed to be directly visible on the Web page.
mark the end of the head of the file.
give a title to the entire page (the Web browser can use the title for whatever purpose it wishes.) This should be in the head section of the page. <br /> end of the title.
mark the start of the body of the file. The body of the file is the main part that is visible on the monitor screen.
mark the end of the body of the file.

a horizontal rule: a line completely across the screen. There is no matching tag.


class Circle
{
// variables



// constructors


// methods


}

Wednesday, 16 May 2007

jar

http://www.dedecms.com/web-art/JSPjiaocheng/20060330/23986.html
如何把java程序编译成.exe文件(就是制作可执行的JAR文件包)

作者:边城狂人

常常在网上看到有人询问:如何把 java 程序编译成 .exe 文件。通常回答只有两种,一种是制作一个可执行的 JAR 文件包,然后就可以像.chm 文档一样双击运行了;而另一种是使用 JET 来进行
编译。但是 JET 是要用钱买的,而且据说 JET 也不是能把所有的 Java 程序都编译成执行文件,性能也要打些折扣。所以,使用制作可执行 JAR 文件包的方法就是最佳选择了,何况它还能保持 Java 的跨平台特性。

下面就来看看什么是 JAR 文件包吧:

1. JAR 文件包

JAR 文件就是 Java Archive File,顾名思意,它的应用是与 Java 息息相关的,是 Java 的一种文档格式。JAR 文件非常类似 ZIP 文件——准确的说,它就是 ZIP 文件,所以叫它文件包。JAR 文件与 ZIP 文件唯一的区别就是在 JAR 文件的内容中,包含了一个 META-INF/MANIFEST.MF 文件,这个文件是在生成 JAR 文件的时候自动创建的。举个例子,如果我们具有如下目录结构的一些文件:

  ==

  `-- test

    `-- Test.class

把它压缩成 ZIP 文件 test.zip,则这个 ZIP 文件的内部目录结构为:

  test.zip

  `-- test

    `-- Test.class

如果我们使用 JDK 的 jar 命令把它打成 JAR 文件包 test.jar,则这个 JAR 文件的内部目录结构为:

  test.jar

  |-- META-INF

  |  `-- MANIFEST.MF

  `-- test

    `--Test.class

2. 创建可执行的 JAR 文件包

制作一个可执行的 JAR 文件包来发布你的程序是 JAR 文件包最典型的用法。

Java 程序是由若干个 .class 文件组成的。这些 .class 文件必须根据它们所属的包不同而分级分目录存放;运行前需要把所有用到的包的根目录指定给 CLASSPATH 环境变量或者 java 命令的 -cp 参数;运行时还要到控制台下去使用 java 命令来运行,如果需要直接双击运行必须写 Windows 的批处理文件 (.bat) 或者 Linux 的 Shell 程序。因此,许多人说,Java 是一种方便开发者苦了用户的程序设计语言。
其实不然,如果开发者能够制作一个可执行的 JAR 文件包交给用户,那么用户使用起来就方便了。在 Windows 下安装 JRE (Java Runtime Environment) 的时候,安装文件会将 .jar 文件映射给 javaw.exe 打开。那么,对于一个可执行的 JAR 文件包,用户只需要双击它就可以运行程序了,和阅读 .chm 文档一样方便 (.chm 文档默认是由 hh.exe 打开的)。那么,现在的关键,就是如何来创建这个可执行的 JAR 文件包。

创建可执行的 JAR 文件包,需要使用带 cvfm 参数的 jar 命令,同样以上述 test 目录为例,命令如下:

jar cvfm test.jar manifest.mf test

这里 test.jar 和 manifest.mf 两个文件,分别是对应的参数 f 和 m,其重头戏在 manifest.mf。因为要创建可执行的 JAR 文件包,光靠指定一个 manifest.mf 文件是不够的,因为 MANIFEST 是 JAR 文件包的特征,可执行的 JAR 文件包和不可执行的 JAR 文件包都包含 MANIFEST。关键在于可执行 JAR 文件包的 MANIFEST,其内容包含了 Main-Class 一项。这在 MANIFEST 中书写格式如下:

Main-Class: 可执行主类全名(包含包名)

例如,假设上例中的 Test.class 是属于 test 包的,而且是可执行的类 (定义了 public static void main(String[]) 方法),那么这个 manifest.mf 可以编辑如下:

Main-Class: test.Test <回车>

这个 manifest.mf 可以放在任何位置,也可以是其它的文件名,只需要有 Main-Class: test.Test 一行,且该行以一个回车符结束即可。创建了 manifest.mf 文件之后,我们的目录结构变为:

  ==

  |-- test

  |  `-- Test.class

  `-- manifest.mf

这时候,需要到 test 目录的上级目录中去使用 jar 命令来创建 JAR 文件包。也就是在目录树中使用“==”表示的那个目录中,使用如下命令:

jar cvfm test.jar manifest.mf test

之后在“==”目录中创建了 test.jar,这个 test.jar 就是执行的 JAR 文件包。运行时只需要使用 java -jar test.jar 命令即可。

需要注意的是,创建的 JAR 文件包中需要包含完整的、与 Java 程序的包结构对应的目录结构,就像上例一样。而 Main-Class 指定的类,也必须是完整的、包含包路径的类名,如上例的 test.Test;而且在没有打成 JAR 文件包之前可以使用 java <类名> 来运行这个类,即在上例中 java test.Test 是可以正确运行的 (当然要在 CLASSPATH 正确的情况下)。



http://sintra.blogbus.com/logs/2006/11/3868713.html

Java技术:生成可执行jar文件的教程
Time:2006年11月20日
若要生成一个名为 cal.jar 的可执行jar文件:(文件名可以是任意合法名字)
(这是我认为简单实用的一种方法,还有很多别的方法在此就不介绍了)
第一 把程序生成的所有字节码文件(即.class文件)放在同一个目录下(如:D:/chat/).
第二 在该目录下新建一个manifest.mf文件,文件内容格式如下(划线中内容):
manifest.mf文件中的格式:
--------------------------------
Main-Class: calDemo

--------------------------------
注意: calDemo代表主类名(即要运行的类名,只能有一个,不要文件扩展名)
Main与Class中间不是下划线,而是短横线
Main-Class:与calDemo中间必须要有空格
Main-Class: calDemo之后必须要回车


文件中还可以加入一些其他信息如:(先不要加,以免出错)

--------------------------------------------
Manifest-Version: 1.0
Created-By: 1.4.1_02 (Sun Microsystems Inc.)
--------------------------------------------

然后用jar命令生成可执行的jar文件,例如:
(执行该命令前先要转到该目录下 D:/chat/ )
jar cvfm cal.jar manifest.mf *.class

jar用法:(仅供参考,初学者可跳过这部分内容)
jar {ctxu}[vfm0Mi] [jar-文件] [manifest-文件] [-C 目录] 文件名 ...
选项:
-c 创建新的存档
-t 列出存档内容的列表
-x 展开存档中的命名的(或所有的〕文件
-u 更新已存在的存档
-v 生成详细输出到标准输出上
-f 指定存档文件名
-m 包含来自标明文件的标明信息
-0 只存储方式;未用ZIP压缩格式
-M 不产生所有项的清单(manifest〕文件
-i 为指定的jar文件产生索引信息
-C 改变到指定的目录,并且包含下列文件:
如果一个文件名是一个目录,它将被递归处理。
清单(manifest〕文件名和存档文件名都需要被指定,按'm' 和 'f'标志指定的相同顺序。

示例1:将两个class文件存档到一个名为 'classes.jar' 的存档文件中:
jar cvf classes.jar Foo.class Bar.class
示例2:用一个存在的清单(manifest)文件 'mymanifest' 将 foo/ 目录下的所有
文件存档到一个名为 'classes.jar' 的存档文件中:
jar cvfm classes.jar mymanifest -C foo/ .

Tuesday, 15 May 2007

常見程式演算

偶然在这里遇到一个关于一些算法问题的网站,里面提供了java的实现。
http://caterpillar.onlyfun.net/Gossip/AlgorithmGossip/AlgorithmGossip.htm

Gladder

Thanks Maro for him to tell me a trick about using Firefox to access some sits such as wikipedia, BBC news and nearly all webs which considered with little political reason, so we are allowed to open.

this technology is call gladder which I had heard before. if I want to access site A, I can land site B, then load A as a part of source B. so, it is not easy for government to filter.

there are many such services like:
proxyhub.co.uk
anonymous.com

here we can use GLADDER in firefox as plug-in

download it from http://gneheix.googlepages.com/gladder

Algorithm::Diff

before that, we need firstly to know something about metric,
here is document in chinese
http://www.core.org.cn/NR/rdonlyres/Sloan-School-of-Management/15-062Data-MiningSpring2003/78318536-A16C-4EC7-879F-C96C123AC7C4/0/linalg.pdf


Dynamic Programming
The following is an example of global sequence alignment using Needleman/Wunsch techniques. For this example, the two sequences to be globally aligned are

G A A T T C A G T T A (sequence #1)
G G A T C G A (sequence #2)

So M = 11 and N = 7 (the length of sequence #1 and sequence #2, respectively)

A simple scoring scheme is assumed where


* Si,j = 1 if the residue at position i of sequence #1 is the same as the residue at position j of sequence #2 (match score); otherwise
* Si,j = 0 (mismatch score)
* w = 0 (gap penalty)

Three steps in dynamic programming

1. Initialization
2. Matrix fill (scoring)
3. Traceback (alignment)

Initialization Step

The first step in the global alignment dynamic programming approach is to create a matrix with M + 1 columns and N + 1 rows where M and N correspond to the size of the sequences to be aligned.

Since this example assumes there is no gap opening or gap extension penalty, the first row and first column of the matrix can be initially filled with 0.

Matrix Fill Step

One possible (inefficient) solution of the matrix fill step finds the maximum global alignment score by starting in the upper left hand corner in the matrix and finding the maximal score Mi,j for each position in the matrix. In order to find Mi,j for any i,j it is minimal to know the score for the matrix positions to the left, above and diagonal to i, j. In terms of matrix positions, it is necessary to know Mi-1,j, Mi,j-1 and Mi-1, j-1.

For each position, Mi,j is defined to be the maximum score at position i,j; i.e.

Mi,j = MAXIMUM[
Mi-1, j-1 + Si,j (match/mismatch in the diagonal),
Mi,j-1 + w (gap in sequence #1),
Mi-1,j + w (gap in sequence #2)]


Note that in the example, Mi-1,j-1 will be red, Mi,j-1 will be green and Mi-1,j will be blue.

Using this information, the score at position 1,1 in the matrix can be calculated. Since the first residue in both sequences is a G, S1,1 = 1, and by the assumptions stated at the beginning, w = 0. Thus, M1,1 = MAX[M0,0 + 1, M1, 0 + 0, M0,1 + 0] = MAX [1, 0, 0] = 1.

A value of 1 is then placed in position 1,1 of the scoring matrix.

Since the gap penalty (w) is 0, the rest of row 1 and column 1 can be filled in with the value 1. Take the example of row 1. At column 2, the value is the max of 0 (for a mismatch), 0 (for a vertical gap) or 1 (horizontal gap). The rest of row 1 can be filled out similarly until we get to column 8. At this point, there is a G in both sequences (light blue). Thus, the value for the cell at row 1 column 8 is the maximum of 1 (for a match), 0 (for a vertical gap) or 1 (horizontal gap). The value will again be 1. The rest of row 1 and column 1 can be filled with 1 using the above reasoning.

Now let's look at column 2. The location at row 2 will be assigned the value of the maximum of 1(mismatch), 1(horizontal gap) or 1 (vertical gap). So its value is 1.

At the position column 2 row 3, there is an A in both sequences. Thus, its value will be the maximum of 2(match), 1 (horizontal gap), 1 (vertical gap) so its value is 2.

Moving along to position colum 2 row 4, its value will be the maximum of 1 (mismatch), 1 (horizontal gap), 2 (vertical gap) so its value is 2. Note that for all of the remaining positions except the last one in column 2, the choices for the value will be the exact same as in row 4 since there are no matches. The final row will contain the value 2 since it is the maximum of 2 (match), 1 (horizontal gap) and 2(vertical gap).

Using the same techniques as described for column 2, we can fill in column 3.

After filling in all of the values the score matrix is as follows:

Traceback Step

After the matrix fill step, the maximum alignment score for the two test sequences is 6. The traceback step determines the actual alignment(s) that result in the maximum score. Note that with a simple scoring algorithm such as one that is used here, there are likely to be multiple maximal alignments.

The traceback step begins in the M,J position in the matrix, i.e. the position that leads to the maximal score. In this case, there is a 6 in that location.

Traceback takes the current cell and looks to the neighbor cells that could be direct predacessors. This means it looks to the neighbor to the left (gap in sequence #2), the diagonal neighbor (match/mismatch), and the neighbor above it (gap in sequence #1). The algorithm for traceback chooses as the next cell in the sequence one of the possible predacessors. In this case, the neighbors are marked in red. They are all also equal to 5.

Since the current cell has a value of 6 and the scores are 1 for a match and 0 for anything else, the only possible predacessor is the diagonal match/mismatch neighbor. If more than one possible predacessor exists, any can be chosen. This gives us a current alignment of

(Seq #1) A
|
(Seq #2) A

So now we look at the current cell and determine which cell is its direct predacessor. In this case, it is the cell with the red 5.

The alignment as described in the above step adds a gap to sequence #2, so the current alignment is

(Seq #1) T A
|
(Seq #2) _ A

Once again, the direct predacessor produces a gap in sequence #2.

After this step, the current alignment is

(Seq #1) T T A
|
_ _ A

Continuing on with the traceback step, we eventually get to a position in column 0 row 0 which tells us that traceback is completed. One possible maximum alignment is :

Giving an alignment of :

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

An alternate solution is:

Giving an alignment of :

G _ A A T T C A G T T A
| | | | | |
G G _ A _ T C _ G _ _ A

There are more alternative solutions each resulting in a maximal global alignment score of 6. Since this is an exponential problem, most dynamic programming algorithms will only print out a single solution.

Now you are ready to explore an example using an advanced scoring scheme.
BL5495 Home Page
Eric C. Rouchka
ecr@ibc.wustl.edu


Advanced Dynamic Programming Tutorial
If you haven't looked at an example of a simple scoring scheme, please go to the simple dynamic programming example

The following is an example of global sequence alignment using Needleman/Wunsch techniques. For this example, the two sequences to be globally aligned are

G A A T T C A G T T A (sequence #1)
G G A T C G A (sequence #2)

So M = 11 and N = 7 (the length of sequence #1 and sequence #2, respectively)

An advanced scoring scheme is assumed where

* Si,j = 2 if the residue at position i of sequence #1 is the same as the residue at position j of sequence #2 (match score); otherwise
* Si,j = -1 (mismatch score)
* w = -2 (gap penalty)

Initialization Step

The first step in the global alignment dynamic programming approach is to create a matrix with M + 1 columns and N + 1 rows where M and N correspond to the size of the sequences to be aligned.

The first row and first column of the matrix can be initially filled with 0.

Matrix Fill Step

One possible (inefficient) solution of the matrix fill step finds the maximum global alignment score by starting in the upper left hand corner in the matrix and finding the maximal score Mi,j for each position in the matrix. In order to find Mi,j for any i,j it is minimal to know the score for the matrix positions to the left, above and diagonal to i, j. In terms of matrix positions, it is necessary to know Mi-1,j, Mi,j-1 and Mi-1, j-1.

For each position, Mi,j is defined to be the maximum score at position i,j; i.e.

Mi,j = MAXIMUM[
Mi-1, j-1 + Si,j (match/mismatch in the diagonal),
Mi,j-1 + w (gap in sequence #1),
Mi-1,j + w (gap in sequence #2)]

Note that in the example, Mi-1,j-1 will be red, Mi,j-1 will be green and Mi-1,j will be blue.

Using this information, the score at position 1,1 in the matrix can be calculated. Since the first residue in both sequences is a G, S1,1 = 2, and by the assumptions stated earlier, w = -2. Thus, M1,1 = MAX[M0,0 + 2, M1,0 - 2, M0,1 - 2] = MAX[2, -2, -2].

A value of 2 is then placed in position 1,1 of the scoring matrix. Note that there is also an arrow placed back into the cell that resulted in the maximum score, M[0,0].

Moving down the first column to row 2, we can see that there is once again a match in both sequences. Thus, S1,2 = 2. So M1,2 = MAX[M0,1 + 2, M1,1 - 2, M0,2 -2] = MAX[0 + 2, 2 - 2, 0 - 2] = MAX[2, 0, -2].

A value of 2 is then placed in position 1,2 of the scoring matrix and an arrow is placed to point back to M[0,1] which led to the maximum score.

Looking at column 1 row 3, there is not a match in the sequences, so S 1,3 = -1. M1,3 = MAX[M0,2 - 1, M1,2 - 2, M0,3 - 2] = MAX[0 - 1, 2 - 2, 0 - 2] = MAX[-1, 0, -2].

A value of 0 is then placed in position 1,3 of the scoring matrix and an arrow is placed to point back to M[1,2] which led to the maximum score.

We can continue filling in the cells of the scoring matrix using the same reasoning.

Eventually, we get to column 3 row 2. Since there is not a match in the sequences at this positon, S3,2 = -1. M3,2 = MAX[ M2,1 - 1, M3,1 - 2, M2,2 - 2] = MAX[0 - 1, -1 - 2, 1 -2] = MAX[-1, -3, -1].

Note that in the above case, there are two different ways to get the maximum score. In such a case, pointers are placed back to all of the cells that can produce the maximum score.

The rest of the score matrix can then be filled in. The completed score matrix will be as follows:

Traceback Step
After the matrix fill step, the maximum global alignment score for the two sequences is 3. The traceback step will determine the actual alignment(s) that result in the maximum score.

The traceback step begins in the M,J position in the matrix, i.e. the position where both sequences are globally aligned.

Since we have kept pointers back to all possible predacessors, the traceback step is simple. At each cell, we look to see where we move next according to the pointers. To begin, the only possible predacessor is the diagonal match.

This gives us an alignment of

A
|
A

Note that the blue letters and gold arrows indicate the path leading to the maximum score.

We can continue to follow the path using a single pointer until we get to the following situation.

The alignment at this point is

T C A G T T A
| | | |
T C _ G _ _ A

Note that there are now two possible neighbors that could result in the current score. In such a case, one of the neighbors is arbitrarily chosen.

Once the traceback is completed, it can be seen that there are only two possible paths leading to a maximal global alignment.

One possible path is as follows:

This gives an alignment of

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

The other possible path is as follows:

This gives an alignment of

G A A T T C A G T T A
| | | | | |
G G A T _ C _ G _ _ A

Remembering that the scoring scheme is +2 for a match, -1 for a mismatch, and -2 for a gap, both sequences can be tested to make sure that they result in a score of 3.

G A A T T C A G T T A
| | | | | |
G G A _ T C _ G _ _ A

+ - + - + + - + - - +
2 1 2 2 2 2 2 2 2 2 2

2 - 1 + 2 - 2 + 2 + 2 - 2 + 2 - 2 - 2 + 2 = 3

G A A T T C A G T T A
| | | | | |
G G A T _ C _ G _ _ A

+ - + + - + - + - - +
2 1 2 2 2 2 2 2 2 2 2

2 - 1 + 2 + 2 - 2 + 2 - 2 + 2 - 2 - 2 + 2 = 3

so both of these alignments do indeed result in the maximal alignment score.
Eric C. Rouchka ecr@ibc.wustl.edu
Feb. 4, 1997
Compuational Molecular Biology Home Page

Kimberley Locke:Based On A True Story

a pop style, you can feel familiar quitly. here list first three songs in this album


歌词标题: Change

所属专辑:Based On A True Story

所属歌手:Kimberley Locke

Sorry for what I forgot to say
But you know how words get in the way baby, lately
Wasn't strong enough to cut right through
All the red tape between me and you, baby
Time escapes me

What's it gonna take to shake these blues
Pushin' through the clouds just to get to you
Can't hold back the storm that's blowin' through, yeah

(Chorus)
I feel a change, babe
Washin' over me
I feel the rains, babe
Comin' to set me free
It's a one way track
Ain't never comin' back
This trains about to leave
I feel a change comin' over me

Never noticed that it's kinda strange
Same story but a different day lately, baby
Gotta get up gotta change the scene
Gotta rip this page from the magazine

(Chorus)

I ain't tryin' to be difficult no, no
I ain't tryin' to be mean
I just gotta do right now
What's best for me, yeah

(Chorus)


CVS使用CVS进行版本管理

#////////////////////////////////////////////////////////////////////// 
# 使用CVS进行版本管理 
# 2000-6-30 
# CVS 1.10.7 
# 
# 
# 
# Per Cederqvist et al 著 
# 廖斌 译 
# 感谢黄箐的输入和排版工作 
# copyrigh: GPL 
# 
#////////////////////////////////////////////////////////////////////// 
  

快捷内容索引 
1. 概述.........................................................1 
2. 代码仓库.....................................................7 
3. 使用CVS开始一个项目..........................................29 
4. 主干版本(Revision).........................................33 
5. 分支与合并...................................................41 
6. Recarsive behavior...........................................49 
7. 增加,删除,更名文件和目录...................................51 
8. 回顾开发历史.................................................57 
9. 放置二进制文件...............................................59 
10 多个开发者的同时工作........................................61 
11 主干版本管理.............................................71 
12 关键字替代................................................73 
13 跟踪第三方代码...............................................77 
14 你的系统如何同CVS交互........................................81 
15 特殊文件.....................................................83 
16 附录 
1) CVS命令导向..................................................85 
2) CVS命令快速参考............................................115 
3) 管理文件的参考习册.........................................127 
4) 影响CVS的所有环境变量......................................141 
5) CVS各版本之间的兼容性......................................143 
6) 遇到的问题.................................................145 
7) Credits....................................................153 
8) 对CVS和这本手册的总是处理..................................155 

目录 ...........................................................157 
    
  

1 概论 

这一章为从未用过CVS的人写的,也许以前也从未用过任何版本控制工具。 

1.1 什么是CVS? 

CVS是个版本控制系统,使用它你可以记录你原代码文件的历史。例如,当软件修改时有时会产生问题(*bugs这里被译为问题),并且你可能在做这次修改后很长时间不会发现这些问题。使用CVS,你可以容易地回顾老的代码版本去发现哪一次的修改导致这些问题。有时候这样会非常有帮助。 
  

你可能会保留你每一次的代码版本,这可能会浪费你很多的代码空间。CVS使用一种聪明的办法保存你的多个版本在一个文件中。它仅仅保留版本间的不同内容。如果你是一个项目中的一组成员之一,CVS也能够帮助你。除非你特别仔细,你很容易覆盖其他人的工作。一些编辑器,例如GNUEmacs,试图去判定一个文件是否被两人同时修改.不幸的是,如果一个人使用其它的编辑器时,这个安全方式将不再有效。CVS使用让不同开发者独立工作的方式解决了这个问题。每一个开发者的工作都在他自己的目录内,并且CVS将在每个开发者的工作完成后进行合并工作。 

CVS是由Dick Grune作为Shell脚本的一个分支而创建的,1986年10月,在它的第6个发行卷时,它被投递到新闻组comp.soures.unix。然而现在的CVS冲突算法中没有任何代码是从这些脚本中来的。 

在1989年3月,Brian Berlinor设计并编写了CVS的代码。Jett.Polk在以后帮助 Brian 完成了CVS 
模型的设计和商业版本支持。 

你可以通过不同的方式得到CVS,包括在Internet上自由的下载。如果你想下载CVS和其它CVS 
文章以得到更多的信息,请看: 

http://www.cyxlic.com 
http://www.loria.fr/~molli/cvs-index.html. 
  

有一个叫 info-cvs 的邮件列表是有关CVS的内容。订阅或取消订阅这个列表请发邮件到 

info-cvs-request@gnu.org 

如果你更喜欢Usenet新闻组,CVS的讨论组为 

Comp.software.confg.mgmt. 

在将来也许会建一个 

Comp.software.confg.mgmt.cvs 

的新闻组, 

但也许这会是Comp.software.confg.mgmt在有太多讨论之后的事情吧。 

你也许想订阅bug-cvs的邮件列表,这在附录H[BUGS]中有更多的信息。订阅它请发Email到 

bug-cvs-reqnest@gnu.org. 

1.2 CVS不能做的事 
(未译) 
2 
  

3 使用CVS开始一个项目 
======================= 
  

因为更改文件名并且把它们移动到另一个目录中不是经常发生的,因此你在开始一个新项目时要做的第一件事是考虑你的文件组织。更改文件名或移动文件并非不可能,但增加了理解上潜在的费解,并且CVS在更改名字的目录上特别的敏感。请参见7.4节[移动文件]。 
(* 译者注: 在Unix中改名和移动是相同的)。 

下一步做的事取决于手中的情况。 

3.1 建立文件 

第一步是在仓库中建立文件。这可以使用多种不同的方法来完成。 

-------------------------------------------------------------------- 

3.1.1 建立一个目录树 

当你开始使用CVS时,你可能已经有几个项目可以使用CVS进行管理了。在这种情况下,最容易的方法就是使用: "import"命令。一个例子是最容易解释如何使用它的。假定你现在有一些你想放到CVS中的文件在"wdir"中,并且你想让它们放在数据仓库中的如下目录: 

"$CVSROOT/yoyodyne/rdir" 

你可以使用如下命令: 

$cd wdir 
$cvs inport -m "Inported Sources" yoyodyne/rdir yoyo start 

如果你没有使用"-m"参数记录一个日志信息,CVS将调用一个编辑器(*译者注:通常是vi)并且提示输入信息。"yoyo"字符串是开发者标笺,"start"是发行标笺。他们没有什么特别的意义,仅仅是因为CVS的需要才放在这里。 

请参见第13章[跟踪代码],得到更多的这方面信息。 

你现在可以检查一下它是否有效了,然后可以删除你原来的代码目录。 

$cd 
$mv dir dir.orig 
$cvs checkout yoyodyne/dir 
$diff -r dir.orig yoyodyne/dir 
$rm -r dir.orig. 

为了避免偶然进入到你原来的目录中去编辑文件,删除原来的代码是个好主意。当然,在你删除之前保留一份备份到其它地方也是明智之举。 

"checkout"命令能使用模块名作为参数(正如前面所有例子)或是一个相对于$CVSROOT的路 
径,如同上面的例子。你应当检查CVS目录中的权限情况是否合适,应当使它们属于某一个 
特定的组。请参见2.2.2.节[文件权限]。 

如果你想"import"的一些文件是二进制代码,你可以使用一些特殊的方法表明这些文件是否 
是二进制文件。请参见C.2节[Wrappers]。 
  

------------------------------------------------------------------------------------ 

3.1.2 从其它版本控制系统建立文件 

如果你有一个其它版本控制系统维护的项目,例如RCS,你也许希望把这些文件放到CVS中, 
并且要保留这些文件的历史。以下是一些讨论。 

从RCS: 
如果你使用RCS,找到RCS文件??通常一个文件名叫"foo.c"的文件会有"RCS/foo.c,v"的RCS文 
件。(但它有可能在其它地方,请看RCS的文档以得到相关信息)。如果文件目录在CVS中不存 
在,那在CVS中创建它。然后把这些文件拷贝到CVS的仓库目录中(在仓库中的名字必须是带 
",v"的原文件;这些文件直接放在CVS中的这个目录下,而非"RCS"子目录中)。这是在CVS中 
一个为数不多的直接进入CVS仓库直接操作的情况,而没使用CVS命令。然后你就可以把它们 
在新的目录下"checkout"了。 

当你把RCS文件移动CVS中时,RCS文件应在未被锁定的状态,否则移动操作时CVS 将会出 
现一些问题。 

从其它版本控制工具 

许多版本控制工具都可以输出"RCS"格式的标准文档。如果你的版本控制工具可以做到这一 
点,直接输出RCS文件,然后按照上面的例子做就可以了。 

如果你的版本工具不能输出RCS文件,那么你必需要写一个脚本文件来,每次取出一个版本 
然后把它放到CVS中去。下面提到的"sccsarcs"脚本就是一个很好的例子。 

从SCCS: 

有一个"sccsarcs"的脚本文件可以做把SCCS的文件转化成RCS文件,这个文件放在CVS原代码 
目录的"contrib"目录中。注意: 

你必须在一台同时安装了RCS和SCCS的机器上运行它。并且,正如其它在"contrib."目录中的 
其它脚本一样。(你的方法也许是变化多端的) 

(*译者注:我并未查看过CVS的contrib目录:-(,因此不知道这下面都有些什么)。 

从PVCS: 

在"contrb"中有一个叫"pves-to-rcs"的脚本可以转换PVCS到RCS文件。你必须在一台同时有 
PVCS和RCS的机器上运行它。 

请看脚本中的注释以得到更多细节。 

3.1.3从无到有建立一个目录树 

建立一个新的项目,最容易的方法是建立一个空的目录树,如下所示: 

$mkdir tc 
$mkdir tc/man 
$mkdir tc/testing 

在这之后,你可以"import"这个(空)目录到仓库中去。 

$cd tc 
$cvs import -m "created directory structure"yoyodyne/dir yoyo 
start 

然后,当新增一个文件时,增加文件(或目录)到仓库中。请检查$CVSROOT中的权限是否正确。 

------------------------------------------------------------------------------------------- 

3.2 定义模块 

下一步是在"moduyes"文件中定义模块。这不是严格需要的,但模块能把相关的目录和文件容易 
关联起来。下面的例子可以充分演示如何定义模块。 

1. 得到模块文件的工作拷贝。 

$cvs checkout CVSROOT/modules 
$cd CVSROOT 

2. 
编辑这个文件并写入定义模块的行。请参见2.4节[管理文件的介绍]。有一个简单介绍,参见C.1节 
[模块文件]。有它的详细描述。你可以使用下面的行定义模块"tc": 

tc yoyodyne/tc 

3. 提交你的更改到仓库 

$cvs commit -m "Added tc module." modules 

4. 发行模块文件 

$cd 
$cvs release -d CVSROOT 

4 
======= 
  

5 分支与合并 
================== 
CVS允许你独立出一个派生的代码到一个分离的开发版本---分支。当你改变一个分支中的文 
件时,这些更改不会出现在主开发版本和其它分支版本中。 

在这之后你可以使用合并(merging)把这些变更从一个分支移动到另一个分支(或主开发版 
本)。合并涉及到使用“cvs update -j”命令,合并这些变更到一个工作目录。你可以确认 
(commit)这次版本,并且因此影响到拷贝这些变更到其它的分支。 

----------------------------------------------------------------------------------- 

5.1 何时应当创建一个分支 

假定tc.c发行版已完成。你正在继续开发tc.c,计划在2个月后发行1.1的版本。在不久以后你的 
客户开始抱怨说代码有些问题,你检查了一下1.0的发行版(请参见4.4节[标笺])并且找到了这 
个错误(这将会有一个小小的更正)。但是,这个当前的版本是处于一个不稳的状态,并且在下 
一个月才能有希望稳定下来。这样就没有办法去发行一个最新的现有版本去更正问题。 

这时就可以去创建基于这棵版本树1.0版的分支。你可以修改这棵树的分支而不影响到主干。当 
修订完成时,你可以选定是否要把它同主干合并或继续保留在这个分支里。 

----------------------------------------------------------------------------------- 

5.2 建立一个分支 

你可以使用“tag -b”去建立一个分支。例如,假定你在工作于一个工作拷贝中: 

$cvs tag -b rel_1_0_patches 

这将基于当前的拷贝分离出一个分支,并分配“rel_1_0_patches”的名字。 

懂得分支是在CVS仓库中创建,而非在工作拷贝中创建的是非常重要的。正上面的例 
子,创建一个基于当前版本的分支不会自动把当前的工作拷贝转到新的分支上。欲知 
详情,请看5.3节[进入 一个分支]。你也可以不参考任何工作拷贝而建立一个分支。 
你可以使用rtag命令: 

cvs rtag -b -r rel-1-0 rel-1-0-patches tc. 

“-r rel-1-0”说明这个分支是基于标志了rel-1-0的版本文件,它不是从最新的版本 
开始分支.这对需要从老的版本进行分支很有用(例如:当修订一个过去的稳定版本时) 

当使用“tag”标志,这个“-b”标志告诉rtag去创建一个分支(而非是这个版本的符号 
连接)。注意标记“rel-1-0”可能对不同的文件有不同的版本数字。因此,这个命令的结果 
是为tc模块建立了一个命名为“rel-1-0-patches”的新版本分支,它是基于标记为“rel-1-0” 
的版本树。 

----------------------------------------------------------------------------------- 

5.3 进入分支 

你可以通过两种方式进入分支:重新checkout或是从现存的拷贝进入。重新checkout使用 
checkout命令并带上“-r”标识,后面是这个分支的标笺(tag)名。(请看5.2[创建一个分支]): 

$cvs checkout -r rel-1-0-patches tc. 

或者如果你已有了一个拷贝,你可以使用“update -r”命令转到这个分支。 

$cvs update -r rel-1-0-patches tc. 

或者使用另一个等同的命令: 

$cd tc 
$cvs update -r rel-1-0-patches 

这对现有拷贝为主干代码或是其它分支都是有效的.上面的命令将把它转到命 
名的分支。同“update”命令相类似。“update -r”合并你所做的任何改变,请注 
意是否有冲突出现。 

一但你的工作拷贝已经转向一个特定的分支。它将一直保持在这个分支内,除非你 
又做了其它的操作。这意味着从这个工作拷贝checkin的变更将加到这个分支的新版 
本中,而不影响到主干版本和其它分支代码。 

想看一个工作拷贝是基于哪一个分支,可以使用“status”命令。在它们输出中查找 
一个“sticky tag”的域(请参见4.9节["sticky tag"],第38页).那就是你的当前分支号。 

$cvs status -v driver.c backend.c 

==================================================================== 
File: driver.c Status: Up-to-date 

Version: 1.7 Sat Dec S 18:25:54 1992 
RCS version: 1.7 /u/cvsroot/yoyodyne/tc/driver.c,v 
Sticky Tag: rel-1-0-patches (branch: 1.7.2) 
Sticky Date: (none) 
Stick Option: (none) 

Existing Tag: 
rel-1-0-patches (branck: 1.7.2) 
rel-1-0 (revision: 1.7) 
  

==================================================================== 
File: backend.c status: Up-to-date 

Version: 1.4 Tue Dec 1 14:39:01 
Rcs Version: 1.4 /u/cvsroot/yoyodyne/tc/ 
Sticky Tag: rel-1-0patches(branch:1.4.2) 
Sticky Date: (none) 
Sticky Option: (none) 

Existing Tag: 
Rel-1-0-patches (branch: 1.4.2) 
Rel-1-0 (revision: 1.4) 
Rel-0-4 (revision: 1.4) 
  

请不要因为每个文件的分支是不同(“1.7.2”和1.4.2")而迷惑。分支的标笺(tag) 
是相同的:"rel-1-0-patches",这些相同标笺的文件是相同分支的。在以上的例子中,分支建 
立之前,"driver.c" 比 "backend.c"有更多的变更,因此它们的版本编号是不同的。请参见5.4节 
[分支和主干版本号]去了解分支如何构建原理的细节。 

-------------------------------------------------------------------------------------- 

5.4 分支与主干版本 

通常,一个文件的主干版本历史是一个增长线(请看4.1[主干版本]页): 
  
    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 !
    +-----+    +-----+    +-----+    +-----+    +-----+
    
然而,CVS并不局限于线性的开发。主干版本可以分为不同的分支,每一个分支可 
以是一个独立的自我维护的开发线。而在一个分支中的变更可以很容易的转移到主干中。 
每一个分支均有一个分支号,由一个“.”分离的十进制奇数组成,分支号的编排依 
赖于它分离出的主线版本。使用分支号允许从一个特定版本分离出多个分支。 

所有的分支版本都依赖于它的原始分离版本号。下面的例子将展示这一点。 

 
                                                         +-------------+

                       1.2.2.3.2  分支 ->             +--! 1.2.2.3.2.1 !

                                                      !  +-------------+

                                                      !
                     +---------+    +---------+    +---------+
    1.2.2 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !----! 1.2.2.2 !
                  !  +---------+    +---------+    +---------+
                  !
                  !
    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !
                  !
                  !  +---------+    +---------+    +---------+
    1.2.4 分支->  +--! 1.2.4.1 !----! 1.2.4.2 !----! 1.2.4.2 !
                     +---------+    +---------+    +---------+

  

你是如何创建具体的分支号的细节通常不是你需要考虑的,但这里谈谈它如何工作。 

当CVS建立一个分支号时,它先得到第一个未用的偶数,开始的数字是2,例如你 
从6.4的主干版本创建分支时,分支号为6.4.2所有分支号码末位为0的号码用于CVS内 
部,(例如6.4.0)。(请参见5.5节[内部分支号]44页)分支1.1.1有特别的含义,请看13章 
[跟踪代码]。 

----------------------------------------------------------------------------------- 

5.5 内部分支号码 

这一节描述CVS的内部分支(magic branches) (* 译者注:magic branch 译为内部分支) 
特性。在大多数情况下,你不用考虑内部分支号码,CVS将为你进行管理。然而,在 
一些特定条件下,它将显现出来,因此理解它如何工作将是有用的。一般的,分支号 
码将由奇数个 "."分隔的十进制整数组成。请看4.1节[版本号码]。然而那并非完全是这 
样的,由于效率的原因,CVS有时插入一个额外的“0”在右末的第二个位置(1.2.4 
变为1.2.0.4,8.9.10.11.12变为8.9.10.11.0.12等)。 

CVS将会很好的将这些变换隐蔽在背后进行,但在一些地方,这种隐蔽并不完全: 

* 内部分支编号会出现在CVS的日志(log)文件中。 
* 你不能够对 "cvs admin" 使用符号分支名。 
  

你可以使用admin命令去为一个分支重新分配一个RCS希望的那样的符号名。如果 
R4patches是一个分配给分支1.4.2(内部分支编号为1.4.0.2)的一个文件"numbers.c"的 
命名,你可以使用如下命令: 

$cvs admin -NR4patches:1.4.2 numbers.c 

它将只在至少一个版本已经提交到这个分支时才会有效。请非常小心不要把一个标 
笺(tag)分配给了一个错误标识号(现在没有看到昨天的一个标笺是如何分配的)。 

---------------------------------------------------------------------------------- 

5.6 合并一个整个分支 

你可以合并一个分支到你的工作目录在“update”命令中“-j 分支号”的标识。使 
用“-j 分支号”将合并这个派生分支点与原版本的最新版之间的变更到你的工作目录 
“-j”的意思是“join”。 

我们现在来考察下面这棵树: 


    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 ! <- 主干
    +-----+    +-----+    +-----+    +-----+
                  !
                  !
                  !  +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !
                     +---------+    +---------+
                     

分支1.2.2分配了一个Rifix的名字.下面的例子假定模块"mod"只包含一个文件"m.c" 

$cvs checkout mod                             # 得到最新的1.4版 
$cvs update -j R1fix m.c                   # 合并所有在分支中的改变,即:1.2与1.2.2.2 
                                                                  # 之间的变化到这个文件的工作目
录. 

$cvs commit -m "Included R1fix    # 建立1.5版 
  

在合并时可能会发生冲突,如果这种情况发生,你可以在提交新版本之前解决它。请 
参见10.3节[冲突的例子]。 

如果你的原文件中包含关键字(请看第12章[关键字替代])。你可能会得到比严格意义 
上的冲突更多的冲突信息。请参见5.10节[合并和关键字],去了解如何避免这个问题。 
"checkout"命令也支持使用"-j"参数。下面的例子同上面所用的例子有相的效果。 

$cvs checkout -j R1fix mod. 
$cvs commit -m "Included R1fix" 

--------------------------------------------------------------------------------- 

5.7 从一个分支多次合并。 


    继续我们上面的例子。现在这棵树看起来是这样的:

    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !                              *
                  !                            *
                  !  +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !
                     +---------+    +---------+


正如上面所讨论的,分支1.2.2.2所引导的“*”号表示从Rifix分支到主干的合并。

    现在我们继续开发Rifix分支:

    +-----+    +-----+    +-----+    +-----+    +-----+
    ! 1.1 !----! 1.2 !----! 1.3 !----! 1.4 !----! 1.5 ! <- 主干
    +-----+    +-----+    +-----+    +-----+    +-----+
                  !                              *
                  !                            *
                  !  +---------+    +---------+    +---------+
    R1fix 分支->  +--! 1.2.2.1 !----! 1.2.2.2 !----! 1.2.2.3 !
                     +---------+    +---------+    +---------+

然后你可能会希望合并新的变更到主干中去。如果你仍使用“cvs update -j Fifix m.c" 
cvs将试图合并你已经合并过的东西,这可能写导致一些不希望发生的东西。 
  

因此,你必须表达清楚你希望只合并未被合并的内容的意思。这样需要使用两个 
“-j“参数。CVS合并从第一个“-j”的版本到第二个“-j”版本的变化。例如,在我们上面 

的例子中: 

cvs update -j 1.2.2.2 -j R1fix m.c 

如果出现的问题是你需要手工指定1.2.2.2的版本号,一个更好的方法是使用: 

cvs update -j R1fix:yesterday -j R1fix m.c 

然而,更好的方式是在每一次合并后重新放一个标笺给Rifix分支,然后使用标 
笺做后的合并: 

cvs update -j merged_from_Rifix_to_trunk -j R1fix m.c 

---------------------------------------------------------------------------------- 

5.8 合并两个任意版本之间的不同 

使用两个“-j”标志,这个update(和checkout)命令能合并两个任意不同的版本 
到你的工作目录。 

$cvs update -j 1.3 backend.c 

将把1.5版本恢复到1.3版本,所以一定要注意版本的顺序。 

如果你在操作多个文件时使用这个选择项,你必须了解在不同的文件之间,版本的 
数字可能是完全不同的。你必须使用标笺(tag)而不是使用版本号来完成多个文件 
的操作。使用两个“-j”操作也能会恢复增加或删除的文件。例如,假定你有一个 
叫“file1”的文件在在于1.1版本中,然后你在1.2版本中删除了它,下面是如何操作的例子: 

$cvs update -j 1.2 -j 1.1 file1 
file1 
$cvs commit -m test 
checking in file1; 
/tmp/cvs-sanity/cvsroot/first-dir/file1 file1,v 
new revision:1.3; previous revision:1.2 done 
$ 

------------------------------------------------------------------------------------ 

5.9 合并能添加和删除文件 

如果你在合并时的改变涉及到添加或删除一些文件,“update -j”将反映这些变化。 
例如: 

cvs update -A 
touch a b c 
cvs add a b c ; cvs ci -m "added" a b c 
cvs tag -b branchtag 
cvs update -r branchtag 
touch d ; cvs add d 
rm a ; cvs rm a 
cvs ci -m "added d , removed a" 
cvs update -A 
cvs update -j branchtag 
  

在这些命令之后(注意要commit),文件'a'将被删除,而文件'd'将被加入到主干。 

------------------------------------------------------------------------------------- 

5.10 合并和关键词 
  

如果你合并的文件包含关键词(参见第12章[关键词替代],73页),你通常将会在 
合并时得到 无数个冲突报告,因为在不同版本中非常不同。 

因此,你常需要在合并时使用“-kk”(参见12.4节[替代模式],75页)选择项。使用 
关键字名字,而非去扩展关键字的值的方法,这个功能选择项确保你合并的版本之间互相相 
同,而避免了冲突。 

   例如:假设你有一个文件如下:

                     +---------+
        br1   ->  +--! 1.1.2.1 !
                  !  +---------+
                  !
                  !
    +-----+    +-----+
    ! 1.1 !----! 1.2 !
    +-----+    +-----+  
  
  

并且你的当前工作目录拷贝为主干(1.2版本)。那么对于以下的合并将会产生一个 
冲突的结果。请看例子: 

$cat file1 
Key $Revision: 1.3 $ 
... 
$cvs update -j br1 
U file1 
RCS file: /cvsroot/first-dir/file1,v 
retrieving revision 1.1 
retrieving revision 1.1.2.1 
Meging differences between 1.1 and 1.1.2.1 into file1 
rscmerge: warning: conflicts during merge 
$ cat file1 
$<<<<<<< file1 
Key $Revision: 1.3 $ 
======= 
Key $Rerision: 1.1.2.1 $ 
$>>>>>>> 1.1.2.1 
... 
  

冲突发生在试图将1.1和1.1.2.1合并到你的工作目录中去的时候。因此,当这个 
关键词从“Revision:1.1"到"Revision:1.1.2.1"时,CVS将试图合并这个变化到 
你工作目录, 这就同你的目录中的变更“Revision:1.2"发生了冲突。 

以下是使用了:“-kk”后的例子: 

$cat file1 
key $Revision: 1.3 $ 
... 
$cvs update -kk -j br1 
V file1 
RCS file: /cvsroot/first-dir/file1,v 
retrieving revision 1.1 
retrieving revision 1.1.2.1 
Merging differences between 1.1 and 1.1.2.1 into file1 
$ cat file1 
key $Revision: 1.3 $ 
... 

在这里版本“1.1”和“1.1.2.1"都扩展为单纯的 "Revision",因此,合并时就不会 
发生冲突了。 

然而,使用 "-kk" 参数还一个主要的问题。即,它使用了CVS通常使用的关 
键字扩展模式。在特殊情况下,如果模式使用针对二进制文件的 "-kb" 
参数。这将会产生问题。因此,如果你的数据库中包括有二进制文件,你将 
必须手工处理这些问题,而不能使用 "-kk"。 

10 多个开发者同时工作 
--------------------- 

当多个开发者同时参与一个项目时,常常会发生冲突。一般经常发生的情况是两个人想 
同时编辑一个文件的时候。它的解决方法之一是文件锁定或是使用保留式的checkout,这种 
方法允许一个文件一次只允许一个人编辑。这是一些版本控制系统的唯一解决方式,包括 
RCS和SCCS。现在在CVS通常使用保留式checkout的方法是使用"CVS admin-1"命令(参见A-6-1AB 
[admin选择项])。在下面将解释这不是一种好的智能的解决方式,当它是许多人喜欢使用的 
一种方式。下面也将讲述可以使用适当的方法来避免两个人同时编辑一个文件,而非使用软件 
的方式强迫达到这一点。 

在CVS中默认的方法是"unreserved checkout"--非保留式的导出。在这种方法下,开发者 
可以同时在他们的工作拷贝中编辑一个文件。第一个提交工作的没有一种自动的方法可以知道 
另一个人在编辑文件。另一个人可能会在试图提交时得到一个错误信息。他们必须使用CVS命令 
使他们的工作拷贝同仓库的内容保持更新。这个操作是自动的。 

CVS可以支持facilitate多种不同的通信机制,而不会强迫去遵守某种规则,如"resered 
checkouts"那样。以下的部分描述这些不同的方式是如何工作的,和选择多种方式之间涉及到 
的一些问题。 

10.1 文件状态 

基于你对导出的文件使用过的操作,和这些文件在仓库中的版本使用过的操作,我们可以 
把一个文件分为几个状态。这个状态可以由"status"命令得到,它们是: 

up-to-date: 
对于正在使用的这个分支,文件同仓库中的最后版本保持一致。 

Locally Modified: 
你修改过文件,但没有"commit"。 

Locally added: 
使用了"add"命令增加文件,但没有"commit" 

Locally Removed: 
你使用了"remove"命令,但没有"commit" 

Needs checkout: 

其他人提交了一个更新的版本。这个状态的名字有些误导,你应当使用"update"而非 

"checkout"来更新新的版本。 

Needs Patch: 
象"Needs checkout"一样,但CVS服务将只给出Patch(补丁)文件,而非整个文件。而 
给出Patch和给出整个文件的效果是相同的。 

Needs Merge: 
一些人提交了一个更新版本,而你却修改过这些文件。 

File had conflicts on merge: 

这同"Locally Modified"相象,只是"update"命令给出了一个冲突信息。如果你还没有 
解决冲突,那么你需要解这个问题,解决冲突的方法参见10.3节[冲突的例子]. 

Unkown: 

CVS不知道关于这个文件的情况.例如,你创建了一个新文件,而没有使用"add"命令 

为了帮助弄清楚文件的状态,"status"也报告工作版本(working 
vevision),这是这个文件是从哪个版本来的,另外还报告"仓库版本"(Repository 
vevision)。这是这个文件在仓库中的这个版本分支的最后版本。 

"status"命令的选择项例在附录B[invoking cvs]。有关"sticky tag"和"sticky 
date"输出内容的信息,参见4.9节[sticky tags]。有关"sticky options"输出内容参见"-k"选择项, 
A.16.1节[update选择项]。 

你应当把"update"和"status"命令放在一起来认识。你使用"update"使你的文件更新到最 
新状态,你使用"status"命令来得到"update"命令将会做何种操作。(当然,仓库中的状态将可 
能会在你运行update之前变化)。事实上,如果你想使用一个命令得到比使用"status"正式的状 
态信息,你可以使用: 

$cvs -n -q -update 

这里"-n"选择项表示不真正执行update,而只显示状态;"-q"选择项表示不打印每个目录的 
名字。有关更多的关于"update"命令的住处参见附录B[使用CVS]。 

10.2 使一个文件更新到最版本 

当你想更新或是合并一个,使用update命令。对于一个不是最新版本的文件,这个命令大略等 
同于"checkout"命令:最新版本从仓库中提出并放到工作目录中。 

当你使用"update"命令时,你修改过的文件在任何情况下不会受到损害。如果在仓库中没有更 
新的版本,"update"时你的代码没有任何影响。当你编辑过一个文件,并且仓库中有更新版本,那 
么"update"将合并所有的变更到你的工作目录。 

例如,想象一个你导出了一个1.4版的文件并且开始编辑它,在某一时候其他人提交了1.5版,然 
后又提交了1.6版,如果你运行update命令,CVS将把1.4版到1.6版之间的变更放到你的文件中。 
如果在1.4版和1.6版之间的改变太靠近于的你一些变更的话,那么一个"覆盖"("overlop")冲突 
就发生了。在这种情况下将输出一个警告信息,然后结果保留的文件中包含了有冲突代码的两个版 
本,由特别的符号所分隔开。请参见A.16节[更新],可以得到关于"update"命令的一个完全的描述。 (http://www.fanqiang.com) 进入【UNIX论坛】

Version Control Systems

Version Control Systems Support
Synchronisation
Rollback
Experimentation
Internationalisation
Historical Record

Version Graphs
Extension
Split
Merge

A Version Control System lets you “check out” versions of a version control file


Locking Vs. Version Tracking

Locking
prevents complicated conflict resolution problems arising
also prevents duplication of effort (two programmers both doing the same thing at the same time)
Version tracking
prevents one person’s work being held up because someone else is using the file they want - or worse still, has forgotten to check the file back in
allows two developers to work on different sections of the same file at once

Lecture 12: Interrupts, Exceptions and I/O

Exceptions are caused by program execution:
Integer arithmetic overflow – result outside [−231, +231)
Division by zero
Illegal instruction – machine code doesn’t make sense
Address error – access to unaligned address
Bus error – access to non-existent address
syscall instruction – when we need an OS request
brk (breakpoint) instruction – used by debuggers
Can be thought of as a synchronous software interrupt. . .

Interrupts arise from external devices:
Disk read complete (via DMA, say)
Memory error (but only with EEC RAM)
User pressed a key on console
Console ready to display another character
Hardware timer expired
Can be thought of as asynchronous hardware exception

Exception Handlers
Hardware saves current PC in a special register
CPU jumps to an exception handler, which
Saves the current processor state
Take appropriate internal action for an exception, or
Deal with the external source of the interrupt
Restores the previous processor state
Resumes user program execution, if possible

BadVAddr $8 offending memory reference
Count $9 current timer; incremented every 10ms
Compare $11 interrupt when Count = Compare
Status $12 controls which interrupts are enabled
Cause $13 exception type, and pending interrupts
EPC $14 PC where exception/interrupt occured


Interrupt mask which of the 8 interrupts are allowed
User mode not simulated by SPIM; always 1
Exception level automatically set during an exception; prevents handler itself being interrupted
Interrupt enable global interrupt enable (or disable)

Monday, 14 May 2007

Pointers and References, Arrays and Strings,Heap and Memory Management

References in Java
A reference is essentially an object’s memory address

Variables containing address are often termed ‘pointers’
A pointer can be thought of as a low-level reference
‘Pointer arithmetic’ – e.g. add offsets, indexing
A pointer is just another type, like an int or a float
Everything stored in memory, pointers included, has an
address: another pointer can even point to it

Arrays
Usually a block of consecutive elements in memory
All same size (s bytes); same offset from one to the next
The i th element is at offset i × s bytes from beginning
Looking up an element of the array is termed ‘indexing’
Assembly equivalent of an int[] in Java would be. . .
a consecutive block of word-sized signed integers
represented by its starting address and length

static data: Contents may change, but size and location doesn’t
In Java, "hello" + "world" contatenates two strings, But neither of the original strings are modified. Instead a new string is created on the heap
The heap is a much larger pool of memory than the stack
Java allocates storage on the heap with the new keyword
All Java objects live on the heap; only primitive types –ints, floats, doubles and references – on the stack
Storage allocated on the heap persist across procedures. Caller can’t access stack storage//-----?????????????

Lecture 10: MIPS Procedure Calling Convention and Recursion

A portion of code within larger program, typically called:
procedures or subroutines in imperative languages like C
methods in OO languages like Java
and functions in functional languages such as Haskell
Functions usually return a value; procedures don’t
Procedures can call other procedures; even themselves

What happens when we call a procedure?
Control hands over to the callee; the caller is suspended
Callee performs requested task
Callee returns control to the caller

Calling Procedures in MIPS Assembly
jal label – jump and link
$ra := PC + 4; PC := [label]-----??????????
Calls procedure at address label
jr src – jump register
PC := src
Issuing j $ra is the assembly equivalent of return

Register $ra contains the return address of the caller
Arguments are passed in registers $a0 to $a3
Results are left in registers $v0 and $v1

The Stack
The stack provides last-in, first out (LIFO) storage
Register $sp points to the topmost word on the stack
By convention, the stack grows downwards
Placing words onto the stack is termed pushing
Taking words off the stack is called popping

Calling Convention
Caller

Push any of $a0-3, $v0-1 and $t0-9 needed later
Place arguments in $a0 to $a3, and stack if necessary
Make the call using jal callee; result in $v0 and $v1
Pop saved registers and/or extra arguments off stack
Callee
Push any of $ra, $s0-$s1 that may be overwritten
Perform desired task; place result in $v0 and $v1
Pop above registers off the stack
Return to caller with jr $ra

The main label is just another procedure


Local Variables
Solution: save initial value of $sp in $fp //---------?????????
Hence local variables always have the same $fp-offset
Note callee must preserve previous value of $fp!

杀人游戏

An occasional chance wake me to search something about Mafia-game, because it seems to be not fashion as a teenage if you do not know it or you can not play。 So, wiki again can tell me much about it even I have no chance to through.


Mafia (game)

For the video game, see Mafia: The City of Lost Heaven.
Mafia

Players 4 or more
Age range 9 and up
Setup time < 6 minutes
Playing time 15-60 minutes2
Random chance Low
Skills required Strategic thought
Team play
Social skills
Roleplay
See Basic gameplay below.
Varies greatly with setting; see online play.
Mafia (also known under the variant Werewolf or Village) is a party game modeling a battle between an informed minority and an uninformed majority. Mafia is usually played in groups with at least five players. During a basic game, players are divided into two teams: 'Mafia members', who know each other; and 'honest people', who know only the number of Mafia amongst them. The goal of both teams is to eliminate each other; in more complicated games with multiple factions, this generally becomes "last side standing".

History
Mafia was created by Dimma Davidoff at the Psychological Department of Moscow State University, in spring of 1986, and the first players were playing in classrooms, dorms, and summer camps of Moscow University. The game become popular in other Soviet colleges and schools and in the 1990s it began to be played in Europe (Hungary, Poland, England, Norway) and then the United States. Mafia is considered to be one of "the 50 most historically and culturally significant games published since 1800" by about.com.

Andrew Plotkin gave the rules a Werewolf theme in 1997 [1] - Looney Labs have sold this version of the game as Are You a Werewolf?, as have Asmodée Éditions under the title Werewolves of Millers Hollow.

David and Jon Huston created another version in the theme of H. P. Lovecraft's Cthulhu Mythos called Do You Worship Cthulhu, published by Toy Vault, Inc. The main card art was completed by Ron Spencer and Walt Howington designed the Instruction graphics.

A variation of Mafia was used in the movie Cry_Wolf. The game involves one wolf, one shepherd, and a number of sheep, with no day and night phases.

Adam Gopnik devotes a chapter to describing the game in "Through the The Children's Gate: at home in New York" (Knopf, 2006).


Basic gameplay

Roles

Players make themselves comfortable in a space such that every player can see every other player. Roles are assigned by a method which is both confidential and verifiable, often by dealing cards; a red or black card signifies the role as either:

Mafia (alternatively, Werewolves or Worshipers)
Innocents (alternatively, Villagers, Townspeople, or Citizens).
Other roles are possible (see Variants).

Generally, gameplay also requires a Narrator (alternatively, Dealer, Don, God, Host, Mayor, Moderator, Proctor, or Storyteller), a person not playing, but moderating the game. The Narrator knows the roles of each of the players and effectively narrates gameplay. However it is possible to have the first dead player become the Narrator when starting with the day phase.


Night
The Narrator tells everyone to close their eyes and lower their heads ("Go to sleep...", "It is now nighttime and all the villagers are asleep...", etc.). This can optionally be accompanied by all players tapping gently to mask the sounds of player movement. On the first night, the Narrator tells the Mafia to open their eyes and acknowledge their fellow Mafia members. Variations at this point:

The Mafia may have a chance to kill off one of the Innocents by show of hands.
On the first night, the Mafia may "kill" the Narrator so that every Innocent gets a chance to participate in at least one execution decision. The Narrator then says in the Morning that he was killed and gameplay continues as usual.
After the first night, Mafia members must secretly communicate during the daytime and then unanimously agree to kill someone during the nighttime without opening their eyes to communicate (i.e., Narrator calls out the names of each player and Mafia must raise a hand to signify a kill). This rule is optional; if it's not included, the Mafia may kill an Innocent in the same method as they did the first night.
In large groups, each Mafia member can kill one person per night.
Other variant characters may have turns to open their eyes to do "business" during the night also (before or after the Mafia).


Day
The Narrator tells everyone to wake up and announces the Mafia's victim. Usually this involves the Narrator telling a story about the murder scene that the remaining players wake up to, and/or a story of how the victim was killed. For example, "The police chief said, 'Bob was shot seven times, stabbed three times and drowned in the river. This is the worst case of suicide I've ever seen.'" This player is "dead" and may no longer participate in the game in any way, and is thus permitted to keep their eyes open at night.

Depending on the variant, The Narrator may reveal the identity of dead players, dead players may reveal themselves by flipping their cards face up (most common version), or the identity of dead players may be left unrevealed. Typically, prematurely revealing one's identity by flipping one's card face up while still alive is considered suicide; in single-execution-per-day variants, this may count as the execution for that day.

During the daytime phase, the players deliberate over which suspected Mafia member they wish to nominate for execution. The Innocents want to execute a Mafia member but all players are allowed to vote. Generally, The Narrator will administer the election, the nominee may be given a chance to defend themselves and a majority is required for the execution to be carried out, although voting variants abound. The same rules apply to players who are executed as to players killed by the Mafia. In some variants, multiple players may be killed during the same day.


Win condition
The game ends either when the last Mafia member is killed (Innocent victory) or the Mafia members gain a majority during the day (Mafia victory). Ties go to the Mafia. The innocents have no way of voting off mafia members at this point, but the mafia can still kill each night. Other variants have different victory conditions.

Note that in a situation of Mafia and Innocent left after a lynching or a morning, the Mafia character usually automatically wins.


Number of Mafia
A game with just one more innocent player than Mafia players during the day phase can still be won by the innocent players (if you start with a night kill, you need two more innocent players than mafia). However, if they make any mistake (i.e. killing an innocent player during the day), they lose.

So the number of "extra villagers" needs to be adjusted to how many mistakes the innocent players are allowed to make during the game. If you have highly skilled players, play with a small difference, if your players tend to just kill random people during the day, increase it. For large parties, kills tend to be much more random, too.

You can start playing mafia with just 3 players, one of which is Mafia (4 if you kill in the first night). This situation however is extremely hard to play lacking any previous knowledge. If the mafia player convinces one of the other two players he wins (draw rule), if he makes both of them suspect him, he loses.

A 5 player setup with just 1 mafia (6 if you kill in the first night) is a bit more interesting. If the innocent players don't happen to identify the mafia player in the first day (which isn't easy), they end up with the same 3 player setup as explained above (or win, if they managed to identify the mafia player), but the remaining players do now have extra information from the behaviour in that previous round.

Empiric values such as 1/3 or 1/4 of players being mafia are common, but again, this depends on the skill of your players. Other players recommend certain combinations such as 2 mafia and 4-5 innocent players, 3 mafia and 6-8 innocent players (and/or discourage larger rounds). There is no mathematically sound 'optimal' value except above "n mafia, n+1 innocent players during the day can still be won by the innocent players" statement.

(Mathematically speaking, this game is not fair. Assuming that all players could read minds, the mafia only wins if they are at least 1/2 of the players in the game. Fortunately, most people can't read minds; but they do usually perform better than a randomizer.)

Variant character roles and rules can change this setup significantly and usually increase or reduce the need for having extra innocent players. But others are targeted at giving the players more data for the 1 mafia vs. 2 innocent "end game"; this data doesn't need to be reliable, but just to give the players more information to base their judgement upon. So when playing with variant character roles, you might or might not have to modify your game parameters.


Variations
Over the years, players have created Mafia variants which utilize alternative names for characters, additional characters, and different methods for conducting deliberation, voting and killing.


Optional roles
Due to the informal nature of the game, roles can be named differently due to cultural differences, thematic flavor, or other reasons. What follows is a general list of types of roles that can be found in Mafia and Werewolf games; it is by nature non-exhaustive.

Protective roles - "Guardian Angel", "Doctor", "Healer", "Archangel", "Bodyguard", "Sorcerer", "Priest", "Protector", "Highlander", "Nurse", etc.
Allied with the Innocents, this person can protect other roles at night. Depending on the variant, they may know the identities of the Mafia and may attempt to persuade the townspeople to kill the members of the mafia rather than another innocent. Sometimes they are allowed to protect themselves. In some games the Nurse obtains the Doctor's abilities if that role dies. Another variant is the "Bulletproof" innocent, who cannot be killed at night by anyone. (In Werewolf, for example, this person could have wolfsbane.)
Investigative roles - "Detective", "Commandant/Super Commandant", "Cop", "Seer", "Spy", "Angel", "Sheriff", "Psychic", "Inspector", "Cattani", "Devil", "Tracker", "Prophet", "Little Girl", etc.
Allied with the Innocents, this person can detect the alignment of other players at night. Occasionally the role will be themed to reveal the role, instead of the alignment. In some variants, the Narrator may lie to the Detective by showing all players as Innocent, all as Guilty, giving reversed results, or random information; these can be termed as "Naïve", "Paranoid", "Insane", or "Random" respectively. A "Tracker" may see what someone's night action was, or the target of their action, and have to deduce information from that. When the Devil exists, he works for the Mafia/Werewolves, trying to discover Innocents with night actions (usually the Angel/investigative roles). The Commandant is equivalent to the detective, though the Super Commandant has an additional protective feature which allows the inspected person (who can be the Commandant, himself) to survive an attempted Mafia killing in the night. The Little Girl in Werewolf is allowed to secretly peek and watch as the werewolves choose their victim.
Killing roles - "Vigilante", "Rambo", "Crazy Veteran", "Bomb", "Terrorist", "Gravedigger", "Hunter", "Village Bicycle", etc.
Aside from Mafia, Werewolves, and Serial Killers (solitary guilty parties), the Innocents may have some roles with the ability to kill at night. The method varies: the Vigilante may have one or more "bullets" for the entire game, or the Bomb/Crazy Vet may only trigger if targeted at night (not necessarily for death) by another role. Variants exist where this person can kill during the daytime cycle (e.g., the Terrorist / Gravedigger), sometimes only if executed during the daytime (eg. the Hunter / Village Bicycle).
Alignment roles - "Miller", "Godfather", "Alpha Wolf", "Traitor", "Village Idiot", "Undercover Cop", "Rat", etc.
Some roles can fool investigations to determine their alignments: the Miller is an Innocent who appears guilty (usually because they are an outsider); the Godfather, on the other hand, appears innocent despite being the leader of the Mafia. The Alpha Wolf is analogous to the Godfather, while the Traitor works with their vote during the day cycle to protect Mafia and hamper the town. The Village Idiot's objective is to get the town to kill him. The Rat or Undercover Cop is a mole within the Mafia group.
Role manipulators - "Role-blocker", "Godfather", "Prostitute", "National Guardsman", "Switcher", "Bus Driver", "Thief", "Witch", "Sorcerer", "Barman", etc.
These roles can stop or alter the night actions of others; for instance, they may prevent a protection or investigation from occurring, or they may change the target. Not all of these roles will be on the side of the Innocents. The Thief may remove the person's role entirely (for instance, by stealing a Vigilante's gun). The Godfather has the ability to recruit innocent players to become Mafia under certain circumstances. This role differs from the Alignment Role of Godfather above.
Association roles - "Freemasons (Masons)", "Siblings", "Cult Leader and Followers", "Cupid", "Lovers" etc.
These roles, usually on the side of the Innocents, know who each other are and what their roles are. Freemasons (Masons) may talk at night, and confirm each other should one become the target of a murder. Siblings typically consist of one Mafia and one Innocent who are related by blood; if one dies, the other commits suicide shortly thereafter. Cult Leaders can recruit at night instead of kill; therefore they act as an independent faction from both the Innocents and Mafia, usually with the ability to talk at night. Cupid can create a Sibling-like relationship between two random players of his/her choosing (called the Lovers) the first night of the game. In this variant, the Lovers can also win the game (regardless of whether they are Mafia, Innocents, or both) by being the last two standing.
Power roles - "Mayor", "Judge", etc.
This role is taken in addition to the assigned role, and it endows the character with additional power over the game (particularly during the daytime). The character could be chosen by random or selected by vote (which could take place before or after roles are assigned). For instance, a Mayor could possess two votes, or a Judge could moderate discussion in parliamentary fashion (to the advantage of their "team"). If the Power character is also an Innocent (and particularly if they have a helpful role), they aid the town. If they are Mafia, this character aids the Mafia.
Additional variations exist, sometimes with even more specialized or complicated abilities.


Optional rules
Mafia killing methods - some variants require all Mafia members to choose the same victim independently for a kill to succeed. Theoretically, this requires them to "communicate" in some way during the daytime and thus increases the chances of detection. This can be achieved either by waking the Mafia members up separately or by having them write their kills. Under this variant, Innocent players write the word 'honest' on a piece of paper; Mafia members write down the name of a player for elimination. If all the mafia notes have the same name on them, that player is considered killed by the Mafia. In some online versions of the game, a particular player (the Godfather, or a designated member of the group) must send in or execute the kill.
Voting variants - some variants have a more complicated process of selecting players to be executed. One variant allows multiple simultaneous nominations and only requires a plurality. Another requires the vote to be unanimous but allows multiple players to be added to the execution queue to ensure unanimity.
"No lynch" or "No kill" - sometimes the Innocents are allowed to vote not to kill anyone on a particular daytime cycle. In general, although the Townspeople will often feel they do not have enough information to kill someone, this is a bad choice because the Townspeople are more likely to vote off a Mafia member than the Mafia are to kill a Mafia member. Furthermore, because a player's role is generally revealed when that player is executed, it provides the Townspeople with reliable and irrefutable information. However, when there are an even number of Townspeople, this can be a good choice. For example, when there are four Townspeople remaining (including one Mafia), voting not to kill someone will result in a 1/3 chance to kill the Mafia the next day as opposed to a 1/4 chance. Note that voting incorrectly in either situation will end the game (resulting in a 1 Mafia/1 Innocent standoff, which is almost always resolved by the Narrator in favor of the Mafia).
Random narrator - to eliminate the inconvenience (especially in large games) of being killed on the first day, this variant has the Innocent who is killed on the first night become the Narrator. The Mafia, of course, has to find a way of informing this person that they are dead without revealing their identities. The writing variant works best. Some players complain that this variant is biased toward eliminating those who are skilled at narrating. This also works the other way round -- there is no kill in the first night (or a fictious player such as the Major or Kenny is killed), but the mafia still wakes up just to learn their identies; the player killed at day becomes the real narrator.
Multiple families - this variant has multiple Mafia families (or a Mafia group and a Werewolf group) who act and win independently of each other. This allows more kills and thus a faster gameplay and also creates the potential for "cross-fire" between the factions.
Imprisonment - this variant allows players to be sent to prison as an alternative to execution. Depending on the variant they can either be sent there by vote or at the discretion of an optional character. Players in prison exist in the separate room possibly with a separate narrator. Murders can happen in prison and certain roles or events have the ability to bring characters back from prison.
Kidnapping - like imprisonment, this variant allows for a Kidnapper character to remove individuals from the game temporarily. If the kidnapper is killed (or, in some cases, investigated by an Investigative role), all kidnapped individuals (whether Mafia or Innocent) return to the game. While kidnapped, characters are considered "dead." However, they can not watch nighttime events because of the possibility of returning.
Wrath of God - this variant allows the Narrator to select in a random and verifiable manner one or more Innocents, (depending on how many total players are in the game) to carry a cost for their death(s). If for example, the Mafia selects said Innocent during the night round, then the Mafia who selected the "protected" player will also die as a result. If during the day round any player leads an accusation towards the "protected" player and that player is voted out, then the original accusor shall die as well. This variant adds to the confusion by allowing players to claim "divine protection" and also makes selecting players to die during the day or night a much more cautious process.
Plague - this variant allows the Narrator to select in a random and verifiable manner one player who dies of plague in the morning. This can occur at set time intervals, or at random, and the player killed in this manner is revealed at the beginning of the next day. A player who targets the plagued player at night may then become plagued as a result of the contact.
Punishment - this variant is generally used as a drinking or risk based game. When a person is killed in the game they are made to take a punishment. In Drinking circles this may be a shot of a spirit such as Gin or Vodka. The punishment is usually decided at the start of the game. A Final punishment could also be added for the losing team too.

Online play
Although Mafia is usually played face to face, playing it online is also common. This adds a new dimension to the game, making it last longer and allowing people to have a record of what others have said and how they have voted. There are many forms of online play: as part for the promotion of the film Cry_Wolf a website was set up to play a similar game using AIM Instant Messenger, pitching wolves against sheep.

Online forum play was first known to be run on the Internet forum Grey Labyrinth by a regular poster from that site. The game requires 1 or 2 moderators to control. A sign up thread is created announcing the game. The game usually starts in the night phase with players messaging the moderator with their choices, and the mafia teams communicating via email before submitting their kill. The moderator will process the choices, write the appropriate death scene for those that were eliminated, and post a dawn scene. Then the players will vote for who they think is mafia. Generally speaking the first day of the online game is very random in nature, but as the game progresses the lynching becomes more strategic and planned.

Themes are the most common method of online play. Any group of well known characters or groups will work. The Simpsons, Hanna Barbera, The Lord of the Rings for example have been used because of their extensive character sets. In themed games, Roles tend to be more creative and relate to the scenes in which they are set. It is not uncommon for major characters to be left out of the balance of roles to allow the mafia teams to lie about who they are. Themes can also be Types - such as a Werewolf-themed game, or more extreme such as Time Travel Mafia or Deep South (a variant with no night phase).

Moderating online play generally requires you to attempt to balance the game well so any team or group has an even chance of winning. This is even more pertinent when using powerful creative roles. The balance is usually 25% mafia - so a 12 player game would entail 3 or 4 mafia depending on the balance of the remainder of the game. A brief listing of the known online variants follows (some would be near impossible to play in real life).

Deep South Mafia - also known as nightless mafia. The game is broken into choice blocks which last a set amount of real life time. During a choice block, players can vote to lynch and/or submit their choices to the moderator. The moderator will action them at a set time. If a player is lynched during that time, the choice block will end immediately, and all votes are nullified and the next block begins. Choices are always made first as part of an update, and then voting. Some moderators may care to flip this rule around. Choices are made in the order received. Common roles for this variant are "Lie Detector" who can detect a lie in a role claim by a player. "Mafia/Serial Killers" who kill during the day at any time. "Advance doctors" who can protect one choice block in advance. "Chef" who can call lunch and end a choice block once.
Grey Labyrinth's Designer Mafia is to have all prospective players invent a role and submit it to the moderator. The moderator tones the roles down to make them playable and then shuffles them up amongst the players.
Location-based games often have maps involved in which players have to travel to different destinations.
MafiaScum.net's Time Travel mafia allows players to alter history with their night choices. Roles are not revealed on death in this variation because players can be brought back to life at any stage. Time travelling roles are usually restricted to prevent chaos. Standard roles are "Coroner" who can investigate a corpse at night. "Blocker" who can prevent a player time travelling. "Serial Killer" who can travel back 1 or 2 nights to kill someone. One of the major changes in Time Travel mafia is that the person with the most votes at the end of a set time is lynched. This means that if a player votes and then dies on a previous night due to a history change, the vote is effectively nullified.
Romanian Mafia Club's Ebony and Ivory mafia games give every player a black ebony ball and a white ivory ball which stand for votes, and the players can effectively work towards lynching or saving others, because every white ball (a vote in favor of that player) takes out a black ball (a vote against him) that he received. The end of the day brings death to the role that has the most black votes.
Mafiascum is an Internet forum where registered members can play a game of Mafia with other people over a message board. Mafiascum has been around since March 2002 and is a direct descendant of the Grey Labyrinth, an Internet forum dedicated to all types of puzzles and games; when Mafia began to dominate the site's traffic and player base, one of the administrators set up a separate forum specifically for those games. Since its creation, membership has grown and diversified, with games now played under different rulesets, in different languages, and at different skill levels. Recently the gamesite moved to an independent server to accommodate these levels of growth. Players have also contributed to a Mafia-specific wiki about game play, strategy, roles, and local players.




http://www.psytopic.com/mag/post/513.html关键词:谎言

杀人游戏最饱受质疑的地方,就是谎言。想在游戏中获胜,关键是不管真话假话,都要说得“理直气壮”。你不能相信其他任何玩家,必须不断制造谎言或者戳穿谎言。

杀手说:一位从事警察工作的玩家对其体会是三个字:可信度。他说,就是简简单单的三个字,可它却成为如今人与人之间最难以把握和捉摸的一种情愫。而“杀人”游戏虽然明里是一个人骗人的游戏,而实则是在教我们如何学会信任。

关键词:友情

“和朋友,可以喝酒,可以旅行,可以逛街,可以结死党,可以相互吹吹牛,拍拍马……但就是不能一起玩‘杀人游戏’。因为,‘杀人游戏’就是一个凶险江湖缩影,一不小心,就暴露了你隐藏很深的底牌,得不偿失。”这是很多人都信奉的一句话。

杀手说:很多圈中人“每次去杀人吧,像回到了家”。他们在游戏中达成默契,结下友谊。这些互为“老朋友”的人,也许不会主动询问你的职业、你的手机号,甚至对你的姓名和年龄都一无所知,但是需要的时候,会给予热情的帮助。

关键词:沉迷

湖南师范大学社会学教授陈成文指出,这类游戏属于心理暗示游戏,游戏者追求游戏的快感和刺激程度往往容易沉迷其中,这对培养一个健康的心态是非常不利,过分沉迷此类游戏必将对身心带来损害。

杀手说:杀手们通常丝豪不掩饰自己对杀人吧的狂热,大部分人都是“一玩就爱上了。这种感觉可能就像吸鸦片。”杀手吴新说:“我知道这样对工作和身体都不好,但就是欲罢不能。”

关键词:过瘾

社会学家仇立平认为,在杀人游戏的过程中,玩家需要根据不同角色或自我辩白或诬陷他人,它让人们有机会在虚拟的游戏世界里扮演“杀手”,过上一把坏人的瘾。

杀手说:徐小姐坦言“喜欢做杀手的感觉,可以主宰其他人的命运,然而,在现实中这是不可能的。”也有人认为,游戏就是游戏,这种模式在现实生活不具备可移植性。“如果像讨伐小学生玩电游一样,批判这个游戏群体,无异于把高理性群体降低成感性人群。”

游戏是一个客观的东西,关键在于游戏者的自控能力。杀人吧受到高知识层的青睐,毕竟对社会危害性不大,存在有合理性,但是也不能排除,游戏过度会产生的心理问题,大脑长期处于兴奋状态,容易造成失衡。
也许,杀人吧的充实,正好填补了现实生活的虚无……

来源: 国际在线
“杀人游戏” 超越游戏

据说“杀人游戏”的雏形源自格林童话:很久以前,一群骑士通过玩纸牌来决定命运,胜者过关,负者葬身毒龙口中。后来,硅谷人由此创立了游戏,并把它作为一种培训工具,用来测评人的心理素质与潜能,培养团队精神。一些敏感的同行们往往只知道这游戏由“海归”们带回,却不知它正是网络人套搬国外商业模式的产物。这个游戏往往能在新员工培训和客户交往时收到奇效,因为它迅速地把陌生的人们挤压到一个封闭的圈子里,让他们休戚与共,大家能迅速熟悉,并了解每个人的个性。虽然它强大的娱乐性掩盖了工具的本质,但究其根源,我们不难理解这种对心理素质和判断力的考验,决不仅仅是在虚拟世界中“发泄”、“减压”那么简单。

“杀人游戏”的参与者面对的是一个信息残缺,虚实难辨的局面,敌友与将来都存在不可预知性,由此,参与者人性的本质和弱点也会不自觉的暴露出来。人的行为模式表现为金字塔形,而塔底则是主导行为的心理动机。据此我们可以把参与游戏者分为这几种类型:

权力型:力图保持权威,充当意见领袖者;

协作型,缺乏主见,追随意见领袖;

控制型:无论成功与否,只求游戏继续,乐于操盘;

成就型,把游戏当作工作,苛求成功,从中获得成就感。

当然还有一种,不擅言辞,容易紧张,往往惨遭错杀者,我们称之“无辜型”。

回头看看,人们在游戏中的表现不正与事业中的表现相符吗?现代人力资源理论认为,苛求人不断发现自己的弱点并不断克服是事业误区,人只有找到自己的核心竞争力并集中发展才不会造成资源浪费。据统计,即便美国也只有1/3受过高等教育的人能找准自己的定位,能通过简单的游戏为人生定位提供参考,游戏的意义早已超越了游戏本身。

林林总总“游戏民”

既然有“股民”、“彩民”世象百态,“游戏民”也不例外。一旦你成为“游戏民”,你就会发现,原来自己如此多疑,记者冷眼旁观了一番“游戏民”们的种种表现。

先看看我们的同行,记者们接近于SOHO一族的生活方式和定题采访的工作习惯造就了强烈的主观意识。他们玩游戏时往往先设立出假想敌,不停搜集素材佐证自己的判断,直觉往往让他们忽略了一些真实的信息。有口舌伶俐的本钱,他们还很容易成为意见领袖,这种领袖往往会误导无辜者,实战中记者就在“老陆”和“老孙”两位胖同行身上证实了这一点。

相比而言技术人员就可信得多,与机器常打交道令他们理性思维极佳,判断时很少感情色彩,“冷酷无情”,评判均衡,误差较小。另外一种IT人则全然把它当作工作,属于成就型,拼命想当法官,而当了良民往往“闹情绪”,常被当奸细“干掉”。

公司领导和下属一同玩游戏不是好事,领导往往会不自觉的成为下属们的意见领袖。尤其是对于规模不大的私企,盲从比率异常的高,而大公司则好得多,“斗争” 也会更有趣。最后给您提供一点秘技:老练的杀手虽然很冷静,少有小动作,但眼神多少会有些惶恐不安或志得意满,盯着他们的眼睛吧,成功率超过60%。