我买了Yair Altmam的书“未记载的MATLAB”;在本书的第2.2章中,他讨论了数据库连接并使用JDBC连接到数据库。我按照书中的步骤和文字进行操作。我下载了mysql-connector-java-5.1.30-bin.jar(来自http://dev.mysql.com/downloads/connector/j/)并输入了以下代码,详见本书:
clear all
%%Initializing JDBC driver
try
import java.sql.DriverManager;
javaclasspath('mysql-connector-java-5.1.30-bin.jar')
driverClassName = 'com.mysql.jdbc.Driver';
try
%This works when the class/JAR is on the static Java classpath
%Note: driver automatically registers with DriverManager
java.lang.Class.forName(driverClassName);
catch
try
%Try loading from the dynamic Java path
classLoader = com.mathworks.jmi.ClassLoaderManager.getClassLoaderManager;
driverClass = classLoader.loadClass(driverClassName);
catch %#ok<*CTCH>
try
%One more attempt, using the system class-loader
classLoader = java.lang.ClassLoader.getSystemClassLoader;
%An alternative, using the MATLAB Main Thread's context
%classLoader =
%java.lang.Thread.currentThread.getContextClassLoader;
driverClass = classLoader.loadClass(driverClassName);
catch
%One final attempt-load directly, like this:
driverClass = eval(driverClassName); %#ok<*NASGU>
%Or like this (if the driver name is known in advance):
driverClass = com.mysql.jdbc.Driver;
end
end
%Now manually register the driver with the DriverManager
%Note: silently fails if driver is not in the static classpath
DriverManager.registerDriver(driverClass.newInstance);
end
%continue with database processing
catch
error(['JDBC driver ' driverClassName ' not found!']);
%do some failover activity
end
%% Connecting to a database
import java.sql.*;
connStr = 'jdbc:mysql://localhost:3306/test';
con = DriverManager.getConnection(connStr,'root','1234');
每次运行代码的尝试都会收到以下错误消息:
??? Java exception occurred:
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost:3306/test
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
Error in ==> undocumentedMATLAB at 45
con = DriverManager.getConnection(connStr,'root','1234');
是否有人遇到此问题或有任何可以帮助我解决问题的建议。
提前致谢。
答案 0 :(得分:2)
我的第一个怀疑是你的java类路径。而不是:
javaclasspath('mysql-connector-java-5.1.30-bin.jar')
使用
javaaddpath('C:\full\path\to\mysql-connector-java-5.1.30-bin.jar')
如果这不是问题,请跳过DriverManager
(实际上并没有多大帮助),看看下面的代码是否有效,(或者它失败了)。
d = com.mysql.jdbc.Driver;
urlValid = d.acceptsURL('jdbc:mysql://localhost:3306/test'); %Should return true
props = java.util.Properties;
props.put('user','root'); props.put('password','1234');
con = d.connect('jdbc:mysql://localhost:3306/test',props)
DriverManager
构造并没有多大帮助。它似乎旨在允许开发人员加载一堆驱动程序,然后连接到任何支持的数据库,而不知道或关心数据库实现是什么(例如Mysql,Postgresql,Oracle等)我从未见过这是一个有用的功能。我认为(希望?)这种方法的使用不太有利于DataSource
构造。
无论如何,如果这是你第一次将Mysql连接到Matlab,你可能最好只使用提供的Driver类进行指导。