I'm trying to connect to a mysql database using Connector/J but get the same message no matter what code I use. I can connect to it manually with the mysql command on debian just fine.
The error is You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '????????????????' at line 1
The latest code is:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class E{
public void connect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(
"jdbc:mysql://192.168.1.3:3306/dbname?user=dbuser&password=dbpw");
}catch( Exception e){
System.out.printf("Something went wrong: "+e.getMessage());
}
}
It fails at the getConnection call. I used print statements to figure this out as NetBeans doesn't have a problem with this (but when I put in a bad host and run it from NetBeans it doesn't complain either).
I get the exact same problem with DataSource
import java.sql.*;
import javax.sql.*;
...
com.mysql.jdbc.jdbc2.optional.MysqlDataSource ds
= new com.mysql.jdbc.jdbc2.optional.MysqlDataSource();
ds.setServerName("192.168.1.3");
ds.setPortNumber(3306);
ds.setDatabaseName("dbname");
ds.setUser("dbuser");
ds.setPassword("dbpw");
conn = ds.getConnection();
...
Something is working because if I put in a bad password I get an access denied message.
I'm using mysql-connector-java-5.1.22-bin.jar and had the same problem with 5.1.21.
These might help you:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL
Problem with connecting to MySQL server
Your getConnection statement should be
conn = DriverManager.getConnection("jdbc:mysql://192.168.1.3:3306/dbname", "dbuser", "dbpw");
Refer this example
I found the following: Stumped SQL Exception for JDBC
In a nutshell, the server my.cnf file needs:
character_set_server=utf8
collation_server=utf8_general_ci
It also said the GCJ (gnu java compiler) is dicey, but I didn't replace it
Related
I'm currently working on an application. We are moving off our file systems and over to our Snowflake database. I can't seem to make a connection to the database - I am continually met with "no suitable driver found" error.
The correct driver was loaded and installed into the build path. Does anyone know whats going on?
The code:
package com.GriefUI.DBComponents;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class Snowflake_Driver {
public static void databaseConnection(HttpServletRequest request, HttpServletResponse response) throws UnsupportedOperationException{
try {
Connection connObject = getConnection();
Statement stmt = connObject.createStatement();
ResultSet rSet = stmt.executeQuery("SELECT * FROM MY_TABLE");
}catch(Exception e) {
e.printStackTrace();
throw new UnsupportedOperationException();
}
}
private static Connection getConnection()
throws SQLException {
try {
Class.forName("net.snowflake.client.jdbc.SnowflakeDriver");
} catch (ClassNotFoundException ex) {
System.err.println("Driver not found");
}
Properties properties = new Properties();
String user = "user";
String pwsd = "password";
String connectStr = "jdbc:snowflake://My_Environment.snowflakecomputing.com";
Connection conn = DriverManager.getConnection(connectStr, user, pwsd);
return conn;
}
}
Build path:
And the related stacktrace:
Driver not found
java.sql.SQLException: No suitable driver found for jdbc:snowflake://My_Environment.snowflakecomputing.com
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.GriefUI.DBComponents.Snowflake_Driver.getConnection(Snowflake_Driver.java:54)
at com.GriefUI.DBComponents.Snowflake_Driver.databaseConnection(Snowflake_Driver.java:20)
at com.GriefUI.Servers.PushServer.doPost(PushServer.java:60)
at com.GriefUI.Servers.PushServer.doGet(PushServer.java:47)
The research I would suggest taking a look at is: https://docs.snowflake.net/manuals/user-guide/jdbc-configure.html
This answer also looked helpful: https://stackoverflow.com/a/54504514/12127815
"adding the jar to classpath, and then running the following command, Class.forName("provided driver name") in the calling class? "
Though a light jar has been asked to be an an enhancement here: "[open]Light driver jar? #174" https://github.com/snowflakedb/snowflake-jdbc/issues/174
Integrating the driver to a project: https://docs.snowflake.net/manuals/user-guide/jdbc-download.html#integrating-the-driver-into-a-project
Specific information copied from the documentation: "To integrate the driver into a project, add the necessary tags to your pom.xml file. For example:
<groupId>net.snowflake</groupId>
<artifactId>snowflake-jdbc</artifactId>
<version>3.9.2</version>
Where the tag specifies the version of the driver you wish to integrate. Note that version 3.9.2 is used in this example for illustration purposes only. The latest available version of the driver may be higher."
Others may have better insights.
I believe the error message may be misleading.
In my case, Snowflake server is behind a firewall/proxy and I get the same error when connection cannot be obtained physically. It all works on the server all right - I get the error when trying to connect to the DB from my local machine that is on the opposite side of the firewall.
So, make sure your application can physically connect to the DB or use a proxy parameter in your java launcher, such as
-Dhttp.proxyHost=a-proxy.host.domain.net -Dhttp.proxyPort=8080 or similar
I just set up a local mySql database. I can connect to it properly through command line and third party software (Navicat..).
Server: localhost:3306
User: root
Password: password
Database name: students
However, when I try to connect with java, I get an error.
CODE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sql {
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306//students?autoReconnect=true&useSSL=false",
"root", "password");
Statement sqlState = conn.createStatement();
} catch (SQLException ex) {
System.out.println("SQLException" + ex.getMessage());
System.out.println("SQLException" + ex.getSQLState());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
OUTPUT:
SQLExceptionCould not create connection to database server. Attempted reconnect 3 times. Giving up.
SQLException08001
Also tried:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306//students", "root", "password");
and
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306//students?autoReconnect=true&useSSL=false","root", "password");
Additional Attempts:
The firewall is disabled.
I installed the Jconnector by putting the .bin.jar in:
C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext
I can see it on the left under JRE in Eclipse and the import doesn't give errors.
NOTEs:
Using mySQL from the terminal, workbench or Navicat gives no errors, any query works, the local server is running properly and the credentials are correct, the user has full admin priviledges.
Any suggestions?
I recently had a similar issue. My issue ended up being that the MySQL server version was 8.0.19, while flyway was using a 5.1.40 version of the java MySQL library.
Once I updated the MySQL library version to 8.0.19, my errors went away.
This exception can have 4 causes:
User does not have privileges to connect to database.
MySQL service is not running.
Incorrect MySQL-Connector Jar.
Database URL is incorrect;.
Check above prerequisites before connecting to MySQL database.
I'm following the JDBC Developer's Guide and trying to test the JDBC thin driver connection using a short java program.
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCVersion
{
public static void main (String args[]) throws SQLException
{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:hr/hr#localhost:1522:orcl");
Connection conn = ods.getConnection();
// Create Oracle DatabaseMetaData object
DatabaseMetaData meta = conn.getMetaData();
// gets driver info:
System.out.println("JDBC driver version is " + meta.getDriverVersion());
}
} //<host>:<port>:<service>
I've tried every possible <host>:<port>:<service> combination but still get a java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
I've successfully tested the OCI driver using another program included in the tutorial....but can't get this one to work. My application will be using the thin driver to connect to the database so my frustration level is....climbing.
Any help is appreciated.
Maybe following comments could explain why you need the sevice name instead of the SID in the URL.
the Oracle JDBC FAQ mention that SIDs will be cease to be supported in one of the next few releases of the database
the Oracle JDBC devolopers guide mention Always connect to a service. Never use instance_name or SID because these do not direct to known good instances and SID is deprecated
the Oracle 2 day + Java developer tutorial mention the syntax jdbc:oracle:driver_type:[username/password]#//host_name:port_number:SID which seems to be a mixture of SID and service name URL (following the other documents and your working example)
in contrast the javadoc for OracleDriver mention only the SID syntax
the Oracle FAQ wiki mention both syntax
.
jdbc:oracle:thin:[USER/PASSWORD]#[HOST][:PORT]:SID
jdbc:oracle:thin:[USER/PASSWORD]#//[HOST][:PORT]/SERVICE
I'm able to connect to my container DB (containing my tables, packages, etc.) using the username/password.
Returns:
JDBC driver version is 12.1.0.2.0
Still can't connect to the tutorial "HR" PDB that comes with the oracle 12c install and which the JDBC tutorial uses.
Edit:
Got it to work using the following:
import java.sql.*;
import oracle.jdbc.*;
import oracle.jdbc.pool.OracleDataSource;
class JDBCVersion
{
public static void main (String args[]) throws SQLException
{
OracleDataSource ods = new OracleDataSource();
ods.setURL("jdbc:oracle:thin:#//localhost:1522/pdborcl.global.XXXXXXXX.com");
ods.setUser("hr");
ods.setPassword("hr");
Connection conn = ods.getConnection();
// Create Oracle DatabaseMetaData object
DatabaseMetaData meta = conn.getMetaData();
// gets driver info:
System.out.println("JDBC driver version is " + meta.getDriverVersion());
}
}
Still don't understand why I need the full global name instead of the instance name.
When connecting to a PDB you should always use the PDB's service name in the connection string. It looks like your PDB's service is "pdborcl.global.XXXXXXXX.com" so that's what you need to use to connect the PDB directly.
Personally I find it easier to use the long URL format:
"jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=pdborcl.global.XXXXXXXX.com)))"
It makes it obvious that you're using a Service name instead of an SID.
The beauty of it is that you can also easily test your connection string with sqlplus:
sqlplus "hr/hr#(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1522))(CONNECT_DATA=(SERVICE_NAME=pdborcl.global.XXXXXXXX.com)))"
If sqlplus works there is not reason why the JDBC Thin driver wouldn't.
Finally you can also connect the root database using a privilege user and then execute "ALTER SESSION SET CONTAINER=pdb" to switch to the PDB. Should you decide to do so you would have to modify your connection string to connect to the root container first. It should have its own service name.
I am implementing a class that needs to connect to a MYSQL database....on a windows system, i had some connection issue which were resolved with changing the "bind-address" paramater in the MYSQL configuration file to localhost and setting the MYSQL connector in the classpath.
I tried the same steps on Red Hat Linux,..but no connection is made. Is it something with the security configuration?. Below is the code i am using to test for a MYSQL connection.
import java.sql.*;
public class test {
static Connection con = null;
public static void main(String[]args) throws SQLException,ClassNotFoundException {
//Load Driver
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/IMS","root","root1");
System.out.println("Database Connected");
} catch(Exception e) {
System.err.println("error connecting database: little challenge" + e);
System.exit(2);
}
}
}
The error being returned is
error connecting database:
little challenge java.sql.SQLException:
Unexpected exception encountered during query.
I believe this means the connection is not being made. How can i resolve this?
Looks like a problem related to use of GCJ. It relates to the connection attempt raising an exception when it reaches an unknown character or one it cannot convert.
Recommendation: use Hotspot (a.k.a. Sun) JVM.
Update: To do so, install the JDK rpm and use alternatives command to set the default JVM version as shown on superuser.
Define port of server
jdbc:mysql://localhost:3306/IMS
You have to add mysql jar file in project.After its work also on linux.
My configuration:
windows XP SP3
JDBC 2005
MS SQL Server 2008 Express, exposed via tcp/ip on port 1433
sqljdbc.jar in class path
I tried:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433/SQLEXPRESS2008;databaseName=Test;selectMethod=cursor", "sa", "");
}
catch (Exception e) {
e.printStackTrace();
}
But it always throws an exception:
java.sql.SQLException: No suitable driver
I also tried the following urls:
localhost:1433/SQLEXPRESS2008
localhost/SQLEXPRESS2008
localhost
Same results.
Any help?
You have the wrong URL.
I don't know what you mean by "JDBC 2005". When I looked on the microsoft site, I found something called the Microsoft SQL Server JDBC Driver 2.0. You're going to want that one - it includes lots of fixes and some perf improvements. [edit: you're probably going to want the latest driver. As of March 2012, the latest JDBC driver from Microsoft is JDBC 4.0]
Check the release notes. For this driver, you want:
URL: jdbc:sqlserver://server:port;DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
It seems you have the class name correct, but the URL wrong.
Microsoft changed the class name and the URL after its initial release of a JDBC driver. The URL you are using goes with the original JDBC driver from Microsoft, the one MS calls the "SQL Server 2000 version". But that driver uses a different classname.
For all subsequent drivers, the URL changed to the form I have here.
This is in the release notes for the JDBC driver.
Download the latest JDBC Driver (i.e. sqljdbc4.0) from Microsoft's web site
Write the program as follows:
import java.sql.*;
class testmssql
{
public static void main(String args[]) throws Exception
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;
databaseName=chapter16","sa","123");//repalce your databse name and user name
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from login");//replace your table name
while(rs.next())
{
String s1=rs.getString(1);
String s2=rs.getString(2);
System.out.println("UserID:"+s1+"Password:"+s2);
}
con.close();
}
}
Compile the program and set the jar classpath viz: set classpath=C:\jdbc\sqljdbc4.jar;.; If you have saved your jar file in C:\jdbc after downloading and extracting.
Run the program and make sure your TCP/IP service is enabled. If not enabled, then follow these steps:
Go to Start -> All Programs -> Microsoft SQL Server 2008 -> Configuration tools -> SQL Server Configuration Manager
Expand Sql Server Network Configuration: choose your MS SQL Server Instance viz. MSQSLSERVER and enable TCP/IP.
Restart your MS SQL Server Instance. This can be done also from the right click menu of Microsoft SQL Server Management Studio at the root level of your MS SQL server instance
If your databaseName value is correct, then use this: DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")
The latest JDBC MSSQL connectivity driver can be found on
JDBC 4.0
The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->
Right Click Project Name --> Properties --> Java Build Path -->
Libraries --> Add External Jars
Also as already been pointed out by #Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname
Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
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");
Statement statement = conn.createStatement();
String queryString = "select * from SampleTable";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
}
}
Hope this helps.
Named instances?
URL: jdbc:sqlserver://[serverName][\instanceName][:portNumber][;property=value]
Note: backward slash
You can try the following. Works fine in my case:
Download the current jTDS JDBC Driver
Put jtds-x.x.x.jar in your classpath.
Copy ntlmauth.dll to windows/system32. Choose the dll based on your hardware x86,x64...
The connection url is: 'jdbc:jtds:sqlserver://localhost:1433/YourDB' , you don't have to provide username and password.
Hope that helps.