打造更强的 Java 支持
2008-12-15 16:37:51 来源:WEB开发网清单 1. 用 DB2 Universal JDBC Driver 建立连接
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class T4DB2Connect {
public static void main(String[] args) {
try {
// load the DB2 Driver
Class.forName("com.ibm.db2.jcc.DB2Driver");
// establish a connection to DB2
Connection db2Conn =
DriverManager.getConnection(
"jdbc:db2://localhost:50000/sample",
"testuser",
"testpassword");
Statement st = db2Conn.createStatement();
String query =
"SELECT job, decimal(avg(salary),10,2) "
+ "FROM ghutchis.staff GROUP BY job";
// execute the query
ResultSet resultSet = st.executeQuery(query);
System.out.println("Job " + "tAverage Salary");
System.out.println("-----" + "t--------------");
while (resultSet.next()) {
String jobType = resultSet.getString("job");
double avgSal = resultSet.getDouble(2);
System.out.println(jobType + "t" + avgSal);
}
resultSet.close();
st.close();
db2Conn.close();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
更多精彩
赞助商链接