我需要将DB2与Java连接。请帮助我在 ECLIPSE* 中将 DB2 与Java 连接 。如果您可以逐步指导我,将对您有很大帮助。请让我知道如何在Eclipse代码段中添加类路径: *
import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class connection { public static void main(String[] argv) { try { Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); } catch (ClassNotFoundException e) { System.out.println("Please include Classpath Where your DB2 Driver is located"); e.printStackTrace(); return; } System.out.println("DB2 driver is loaded successfully"); Connection conn = null; PreparedStatement pstmt = null; ResultSet rset=null; boolean found=false; try { conn = DriverManager.getConnection("jdbc:db2:sabarish","db2admin","Murugasaranam"); if (conn != null) { System.out.println("DB2 Database Connected"); } else { System.out.println("Db2 connection Failed "); } pstmt=conn.prepareStatement("Select * from bo"); rset=pstmt.executeQuery(); if(rset!=null) { while(rset.next()) { found=true; System.out.println("Class Code: "+rset.getString("clcode")); System.out.println("Name: "+rset.getString("name")); } } if (found ==false) { System.out.println("No Information Found"); } } catch (SQLException e) { System.out.println("DB2 Database connection Failed"); e.printStackTrace(); return; } } }
运行代码时,出现以下异常:
java.lang.ClassNotFoundException: COM.ibm.db2.jdbc.app.DB2Driver at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at connection.main(connection.java:11)
您需要更正软件包名称。
Class.forName("com.ibm.db2.jdbc.app.DB2Driver");
要在项目中添加.jar =>项目+属性+ Java构建路径+选择“库”选项卡+添加外部Jars …