Using SQLServer JDBC Driver in MATLAB - java

I need to connect to a SQLServer database from inside Matlab.
Caveats:
Buying licenses to Matlab's Database Toolbox is not an option-- I can only use core-Matlab and Java.
I cannot assume anything about the Java paths when Matlab is initialized.
Please don't tell me to use Python. I already know that but the company I work for does not...
Here's what I've done so far...
I've downloaded the SQL Server JDBC Driver from here.
I've created a sandbox directory, contents pictured below...
Here is my Matlab code.
% Connection params
server = 'myServerName';
port = 1433;
dbname = 'myDatabase';
user = 'user1';
pass = 'password';
url = sprintf('jdbc:sqlserver://%s:%d;DatabaseName=%s',server,port,dbname);
% Importing Java libraries
import java.sql.*;
import java.sql.DriverManager;
import java.sql.DriverManager.*;
% Add the Microsoft SQL Server JAR to Java path
javaaddpath('<path_to_this_folder>\sqljdbc41.jar'); %for JRE7
import com.microsoft.sqlserver.jdbc.*
% Try to instantiate the JDBC Driver
% This way DOES work
% (https://stackoverflow.com/questions/24438359/connecting-matlab-and-mysql-with-the-jdbc-driver)
if true
d = com.microsoft.sqlserver.jdbc.SQLServerDriver;
urlValid = d.acceptsURL(url);
props = java.util.Properties;
props.put('user',user);
props.put('password',pass);
con = d.connect(url, props);
% This way DOES NOT work.
%I referred to the sample code included with the JDBC to write this.
else
% Matlab Doc says this is similar to calling...
% Class.forName(...)
javaObjectEDT('com.microsoft.sqlserver.jdbc.SQLServerDriver');
driver = DriverManager.getDriver(url);
con = DriverManager.getConnection(url, user, pass);
end
It appears that for whatever reason, the DeviceManager is not loading the driver properly. The method DriverManager.getDriver(url) is throwing an Exception...
Java exception occurred:
java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(Unknown Source)
Is there a way to fix this or should I just roll with connecting directly through the Driver itself? I can't think of a reason why it matters. Will there be any consequences? Should I go with a DataSource approach instead?
Thanks!

You might want to try adding the driver to the static Java path rather than the dynamic Java path. Whenever I’ve worked with database drivers, they seem to have trouble if they’re on the dynamic path; I’m not sure why exactly, but they seem to need loading in a particular way that doesn’t work nicely if they’re on the dynamic path.

Related

Java JDBC Driver stops working after initial execution [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 1 year ago.
I am currently making a backend reporting system (for a voting system assignment) using Java on VS Code, I am connecting to a MySQL database using the JDBC library in order to do calculations and stats and so on. So what happens is that once I create a project file and include the mysql-connector-java-8.0.25.jar in the referenced libraries, I can connect to the DB and retrieve data from the tables just fine, but after a few executions I no longer get output and it shows me the error "java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver".
Can anyone tell me why this is happening and how to fix this? There are no changes that I know of taking place in the Environment Variables (at least from what I can see in Windows path list) unless something is being overwritten somewhere or that it's a bug of some sort. Any advice would be greatly helpful, I've been unable to figure this out all day
This is what my ReportSystem.java looks like...
import java.sql.*;
public class ReportSystem
{
public static void main(String[] args)
{
//Test driver connection/registration
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ElectionDB","<username>","<password>");
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM ElectionDB.Votes");
int typeColumn = 1;
int districtColumn = 2;
//Output results line by line
while(result.next())
{
System.out.println(result.getString(typeColumn));
System.out.println(result.getString(districtColumn));
}
//Remember to close the connection
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
My file structure as in the directory is as follows:
ReportSystem
>src > ReportSystem.java
> ReportSystem.class
>lib
>.vscode > settings.json
The JRE system library used is: [jdk-16.0.1]
The Referenced Libraries contains: [mysql-connector-java-8.0.25.jar]
Screenshot for context Project Setup in VS Code
I'm able to get result after running code 20 times continuously by clicking the run button. The only difference is the JDBC connection string, which is copied directly by right clicking the MYSQL connection:
So in my project, the connection string is like:
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=username","<username>","<password>");
OR
You could try
String url="jdbc:mysql://localhost:3306/ElectionDB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"
For your reference, OS Infomation:
MySQL: 8.0 // mysql-connector-java-8.0.25.jar
VSCode: 1.56.2 //
java.home: JDK16 // Debugger for Java: 0.33.1

How can I connect to oracle with jdbc from python?

Seeing the last part of this article, I'm dying to do the same on my Eclipse.
import jpype
import jaydebeapi
JHOME = jpype.getDefaultJVMPath()
jpype.startJVM(JHOME, '-Djava.class.path=/ojdbc8-full/ojdbc8.jar')
con = jaydebeapi.connect('oracle.jdbc.driver.OracleDriver','jdbc:oracle:thin:XXXXXX/XXXXXX#//99.99.99.99:1521/ABC')
cur = con.cursor()
cur.execute('select dummy from dual')
r = cur.fetchall()
print(r[0][0])
cur.close()
con.close()
And these message have appeard on my screen though, to tell the truth I have no knowledge about JAVA.
raise _RUNTIMEEXCEPTION.PYEXC("Class %s not found" % name)
jpype._jexception.RuntimeExceptionPyRaisable: java.lang.RuntimeException: Class oracle.jdbc.driver.OracleDriver not found
So far, JAVA_HOME environment variable on my computer is the following.
java home
Since I don't know which jdbc driver is appropriate for my environment, I haven't actually done anything, he recommended downloading though.
And I don't know even where I should put that driver I would get later.
If someone tell me what I should do fast of all, I would be so happy! Thanks.

COMPARING Visual Basic sql to Java sql

This is my way of connecting my project on Visual Basic (winform application) and trigger the SELECT STATEMENT to the SQLSERVER, my problem now is that I dunno if this is the same way to connect my project on JAVA application. (of course I know that it should be Imports java.sql.* instead of Imports System.Data.SqlClient)
Imports System.Data.SqlClient
Try
Dim querystring As String = "SELECT MAX(pIDNo) FROM dbo.Patients"
Using connection As New SqlConnection("Data Source=****;Initial Catalog=****;Persist Security Info=True;User ID=****;Password=****")
Dim command As New SqlCommand(querystring, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader
Dim value = String.Empty
While reader.Read
value = reader.GetString(0)
End While
txtPNumber.Text = Today.Year.ToString().Substring(2, 2) & Today.Month.ToString().PadLeft(2, "0") & (Integer.Parse(value.Substring(4, value.Length - 4)) + 1).ToString("D4")
End Using
Catch ex As Exception
txtPNumber.Text = Today.Year.ToString().Substring(2, 2) & Today.Month.ToString().PadLeft(2, "0") & num.ToString("D4")
End Try
It's kinda hard to understand on how to connect my java application to SQLSERVER because I'm lack of information regards with suchs things. could anyone tell me how to do it?
You can connect to SQL Server from Java using Microsoft JDBC Driver for Java: https://msdn.microsoft.com/en-us/sqlserver/aa937724.aspx
You can view some sample applications that use Microsoft JDBC Driver for Java here: https://msdn.microsoft.com/en-us/library/aa342346%28v=sql.110%29.aspx

Issues with Class.forName in Java code using Eclipse IDE

I am using Eclipse IDE Version: Helios Service Release 2 and JDK version 1.6. I have SQL Server 2008 installed on my system. I have downloaded Microsoft JDBC driver and included the path of the jar file in Eclipse IDE-> Project Properties->Java build Path-> Libraries -> Add External jars.
I have written this piece of code for database connection:
package com.ucs.test;
import java.sql.*;
public class ConnectDatabase {
Connection DBconnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
}
But I get the following errors:
Syntax error on token "DBconnection", VariableDeclaratorId expected after this token
Syntax error on token "drivername", VariableDeclaratorId expected after this token
Syntax error on token(s), misplaced construct(s)
I am new to Java and Eclipse IDE. Please help me in correcting this errors. A quick help is appreciated.
These statements:
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
are currently just part of the class - not in a method, or constructor, or static initializer etc. You probably want to put them in a constructor. The previous ones are okay, as they're variable declarations - although whether you really want them to be instance variables is a different matter.
Also note that driverName isn't declared anywhere in the code you've given.
On a tangential note, if you're sufficiently new to Java that you're running into this sort of thing, you should abandon your current code completely: you're currently trying to run before you can walk. Talking to databases correctly is non-trivial, and trying to learn how to do that while also learning Java syntax is going to be messy. Start with simple console apps that let you learn the language and some of the core types (strings, numbers, collections etc) and then move on to databases.
Class.forName(drivername);
DBconnection = DriverManager.getConnection(dbName,userName,password);
You can not put them where you placed in your class, You have to put them in constructor/method, like :
public class ConnectDatabase {
Connection dbConnection = null;
String dbName = "silkopenview";
String userName = "SilkTestAdmin";
String password = "Nbv12345";
public Connection getConnection() {
Class.forName(drivername);
dbConnection = DriverManager.getConnection(dbName,userName,password);
return dbConnection;
}
}
You need to place your statements in a method rather than in the class block.
Class.forName(drivername);
and
DBconnection = DriverManager.getConnection(dbName,userName,password);
Given that you're using SQL Server, you will need to declare your driverName:
final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

How to make Java work with SQL Server?

I know this is a basic question, but I can't seem to find an answer and I apologize, if this question is way too stupid, but here we go:
I am supposed to work with SQL Server (no problem so far) and with Java (love java, so no problem here either), but now: What am I supposed to do to make the combination work?
I got: JRE 1.6 and the sqljdbc4.jar ... Before I put sqljdbc4.jar into my classpath I had sqljdbc.jar in it and with a test-program I got this exception:
21.08.2009 09:26:59 com.microsoft.sqlserver.jdbc.SQLServerConnection <init>
SCHWERWIEGEND: Die Java-Laufzeitumgebung (Java Runtime Environment, JRE), Version 1.6,
wird von diesem Treiber nicht unterstützt. Verwenden Sie die Klassenbibliothek
'sqljdbc4.jar', die Unterstützung für JDBC 4.0 bietet.
java.lang.UnsupportedOperationException: Die Java-Laufzeitumgebung (Java Runtime
Environment, JRE), Version 1.6, wird von diesem Treiber nicht unterstützt. Verwenden
Sie die Klassenbibliothek 'sqljdbc4.jar', die Unterstützung für JDBC 4.0 bietet.
at com.microsoft.sqlserver.jdbc.SQLServerConnection.<init>(SQLServerConnection.java:223)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:840)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at msSqlTest.DB.dbConnect(DB.java:13)
at msSqlTest.TestConnection.main(TestConnection.java:7)
Sorry for the German ... It basically means, that I should use sqljdbc4.jar, b/c the JRE I am using is not supported by the driver. So I put sqljdbc4.jar into my classpath, but it didn't work, so I am kinda lost, what I could do.
Maybe someone could tell be in an idiot-proof way what I should do :(
Oh yeah, here is the test appI use:
import java.sql.*;
public class TestConnection{
public static void main(String[] args){
// Neue DB und los geht's :)
DB db = new DB();
db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );
}
}
class DB{
public void dbConnect( String db_connect_string,
String db_userid,
String db_password){
try{
Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" );
Connection conn = DriverManager.getConnection(
db_connect_string,
db_userid,
db_password);
System.out.println( "connected" );
}
catch( Exception e ){
e.printStackTrace();
}
}
};
Have you tried the jtds driver for SQLServer?
Do not put both the old sqljdbc.jar and the new sqljdbc4.jar in your classpath - this will make it (more or less) unpredictable which classes are being used, if both of those JARs contain classes with the same qualified names.
You said you put sqljdbc4.jar in your classpath - did you remove the old sqljdbc.jar from the classpath? You said "it didn't work", what does that mean exactly? Are you sure you don't still have the old JAR in your classpath somewhere (maybe not explicitly)?
The driver you are using is the MS SQL server 2008 driver (sqljdbc4.jar). As stated in the MSDN page it requires Java 6+ to work.
http://msdn.microsoft.com/en-us/library/ms378526.aspx
sqljdbc4.jar class library requires a
Java Runtime Environment (JRE) of
version 6.0 or later.
I'd suggest using the 2005 driver which I beleive is in (sqljdbc.jar) or as Oxbow_Lakes says try the jTDS driver (http://jtds.sourceforge.net/).
Maybe a little late, but using different drivers altogether is overkill for a case of user error:
db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );
should be either one of these:
db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );
(using named pipe) or:
db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );
using port number directly; you can leave out 1433 because it's the default port, leaving:
db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );
For anyone still googling this, go to \blackboard\config\tomcat\conf and in wrapper.conf put an extra line in wrapper.java.classpath pointing to the sqljdbc4.jar and then update the wrapper.conf.bb as well
Then restart the blackboard services and tomcat and it should work
It won't work by simply setting your java classpath, you have to set it up in the blackboard config files to point to your jar file with the jdbc library
I had the same problem with a client of my company, the problem was that the driver sqljdbc4.jar, tries a convertion of character between the database and the driver. Each time that it did a request to the database, now you can imagine 650 connections concurrently, this did my sistem very very slow, for avoid this situation i add at the String of connection the following parameter:
SendStringParametersAsUnicode=false, then te connection must be something like url="jdbc:sqlserver://IP:PORT;DatabaseName=DBNAME;SendStringParametersAsUnicode=false"
After that, the system is very very fast, as the users are very happy with the change, i hope my input be of same.
Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).
I used 1.5 for the other server, so I waisted a lot of time on this.
Tricky issue.
If you are use sqljdbc4.jar, use the following code
ResultSet objResultSet = objPreparedStatement.getResultSet();
if (objResultSet == null) {
boolean bResult = false;
while (!bResult){
if (objPreparedStatement.getMoreResults()){
objResultSet = objPreparedStatement.getResultSet();
bResult = true;
}
}
}
objCachedRowSet = new CachedRowSetImpl();
objCachedRowSet.populate(objResultSet);
if (CommonUtility.isValidObject(objResultSet)) objResultSet.close();
objResultSet = null;
What about the official JDBC 4.0 compatible JDBC driver from Microsoft?

Categories

Resources