我最近开始使用JDBC。我从ubuntu软件中心安装了JDBC驱动程序,并使用JDBC运行我的第一个Java程序。JDBC类未发现异常
import java.sql.*
public class db
{
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/emp";
static final String USER= "username";
static final String PASS="password";
public static void main(String [] args)
{
Connection conn=DriverManager.getConnection(JDBC_DRIVER);
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database");
System.out.println("Creting statement");
String sql;
stmt=conn.createStatement();
sql="select id, first last, age from Employee";
ResultSet rs= stmt.executeQuery(sql);
while(rs.next())
{
int id=rs.getInt("id");
int age=rs.getInt("age");
String first=rs.getString("first");
String last=rs.getString("Last");
System.out.print("ID: "+id);
System.out.print(", Age: " +age);
System.out.print(", First: "+first);
System.out.println(", Last: "+last);
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(stmt!=null)
conn.close();
}
catch(SQLException se)
{
se.printStackTrace();
}
}
}
}
我创建了“emp”数据库,我试图用JDBC浏览它的内容。当我使用
javac db.java
一切正常。但是,当我运行它通过
java db
它给我java.lang.classnotfoundException。我将CLASSPATH = CLASSPATH://user/share/java/mysql-connector-java.jar包含到了bashrc文件中。任何人都可以帮我解决这个问题吗?
如果您使用任何IDE将该jar文件添加到“WEB -INF/lib',如果它是一个Web应用程序,将它添加到'lib'文件夹并尝试它。 –
不,vi和bash –
我强烈建议你使用像Maven,Ant + Ivy,Gradle等构建和依赖管理工具,而不是手动编译和设置类路径。 –