最近做SAP项目,需要用到Sybase SQL Anywhere 12,现将连接数据库代码附上,以作备份。
以下代码需要引入sajdbc4.jar到web-inf下的lib文件夹中。
sajdbc4.jar在Sybase SQL Anywhere 12安装目录下E:\Program Files\SQL Anywhere 12\Java\sajdbc4.jar路径中可以找到。
其中"uid=Test,pwd=test "为自己新建数据库的用户名和密码。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class DBUtil {
private static final String DRIVER = "sybase.jdbc4.sqlanywhere.IDriver"; // jdbc4.0
private static final String URL = "jdbc:sqlanywhere:uid=Test;pwd=test";
public DBUtil() {
}
public static void main(String[] args) {
DBUtil demo = new DBUtil();
try {
demo.select();
} catch (Exception e) {
e.printStackTrace();
}
}
public void select() throws Exception {
Connection con = this.getConnection(DRIVER, URL);
PreparedStatement pstmt = con.prepareStatement("SELECT GETDATE() ");
ResultSet rs = pstmt.executeQuery();
this.processResult(rs);
this.closeConnection(con, pstmt);
}
private void processResult(ResultSet rs) throws Exception {
if (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
int colNum = rsmd.getColumnCount();
for (int i = 1; i <= colNum; i++) {
if (i == 1) {
System.out.print(rsmd.getColumnName(i));
} else {
System.out.print("\t" + rsmd.getColumnName(i));
}
}
System.out.print("\n");
System.out.println("-----------------------");
do {
for (int i = 1; i <= colNum; i++) {
if (i == 1) {
System.out.print(rs.getString(i));
} else {
System.out.print("\t"
+ (rs.getString(i) == null ? "null" : rs
.getString(i).trim()));
}
}
System.out.print("\n");
} while (rs.next());
} else {
System.out.println("query not result.");
}
}
private Connection getConnection(String driver, String url)
throws Exception {
Class.forName(driver);
return DriverManager.getConnection(url);
}
private void closeConnection(Connection con, Statement stmt)
throws Exception {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
}
}
参考博客:http://blog.chinaunix.net/uid-16765068-id-4093220.html
参考文档:http://www.quickprogrammingtips.com/java/connecting-to-sybase-sql-anywhere-database-in-java.html