سؤال

Other similar questions on StackOverflow didn't answer my question in this area. I have this script that doesn't work, and I am wondering how to get it to work:

// beanshell script script.bsh
import com.mysql.jdbc.Driver; 
import java.sql.Connection;  
name="com.mysql.jdbc.Driver"; 
c = getClass( name ); 
c = BshClassManager.classForName( name );  // equivalent 

And the error I get is:

// Debug: getResolvedMethod cache MISS: class bsh.BshClassManager - classForName
// Debug: Searching for method: classForName( java.lang.String ) in 'bsh.BshClassManager'
// Debug: Looking for most specific method: classForName
bsh.UtilEvalError: Cannot reach instance method: classForName( java.lang.String ) from static context: bsh.BshClassManager
        at bsh.Reflect.checkFoundStaticMethod(Unknown Source)
        at bsh.Reflect.resolveJavaMethod(Unknown Source)
        at bsh.Reflect.resolveExpectedJavaMethod(Unknown Source)
        at bsh.Reflect.invokeStaticMethod(Unknown Source)
        at bsh.Name.invokeMethod(Unknown Source)
        at bsh.BSHMethodInvocation.eval(Unknown Source)
        at bsh.BSHPrimaryExpression.eval(Unknown Source)
        at bsh.BSHPrimaryExpression.eval(Unknown Source)
        at bsh.BSHAssignment.eval(Unknown Source)
        at bsh.Interpreter.eval(Unknown Source)
        at bsh.Interpreter.source(Unknown Source)
        at bsh.Interpreter.main(Unknown Source)

The documentation says it should exist.

هل كانت مفيدة؟

المحلول

According to the http://beanshell.org/manual/classpath.html#Loading_Classes_Explicitly documentation you're free to choose either getClass( name ) or BshClassManager.classForName( name ) to load the driver. Note also the // equivalent comment.

Perhaps the documentation just gave a wrong example of how to use the BshClassManager properly. But as it's just an "equivalent" you could remove that altogether. The getClass() should work just fine.

نصائح أخرى

Thanks to BalusC, this was the answer:

// debug();
// addClassPath("mysql-connector-java-5.1.15.jar"); 
import com.mysql.jdbc.Driver; 
import java.sql.Connection;  
import java.sql.DriverManager; 

System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "mydb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "password";
try {
    c = getClass( driver ); 
    conn = DriverManager.getConnection(url+dbName,userName,password);
    System.out.println("Connected to the database");
    conn.close();
    System.out.println("Disconnected from database");
 } catch (Exception e) {
  e.printStackTrace();
 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top