【发布时间】:2014-04-24 21:11:54
【问题描述】:
我正在编写我的第一个 java 程序,它应该连接到数据库。我已经成功创建了 JDBC 驱动程序(4.0 版),并且 ping 成功。接下来,我正在尝试下面的代码,但它不起作用。我发现我需要导入 com.sybase.*;为了那个原因。这给出了编译错误,指出无法解析导入。 (我对java很陌生。这是我的第一个程序,所以非常感谢任何帮助)。谢谢。我正在使用 sybase 15.x。
enter code here
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.sybase.jdbc4.jdbc.*; --> this is where I see error.
public class DBConnTest {
// JDBC driver name and database URL
//static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//static final String DB_URL = "jdbc:mysql://localhost/EMP";
static final String JDBC_DRIVER = "Sybase15";
static final String DB_URL = "jdbc:sybase:Tds:<IP>:<PORT>/<DB>?CHARSET=iso_1";
// Database credentials
static final String USER = "abc";
static final String PASS = "def";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
//Class.forName("com.sybase.jdbc4.jdbc.SybDriver");
Class.forName("com.sybase.jdbc4.jdbc.SybDriver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT ID,AGE,FIRST,AST FROM testtbl";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("ID");
int age = rs.getInt("AGE");
String first = rs.getString("FIRST");
String last = rs.getString("LAST");
//Display values
System.out.print("ID: " + id);
System.out.print(", AGE: " + age);
System.out.print(", FIRST: " + first);
System.out.println(", LAST: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
【问题讨论】:
标签: java jdbc import sybase sap-ase