Error while connecting to Cloud SQL using jdbc driver - java

I have written a basic java code to connect to my Cloud SQL instance. I have added the mysql jar connector in this project.
import java.sql.*;
class MysqlCon {
public static void main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://project-name:us-central1:test-instance", "username", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from testing");
while (rs.next())
System.out.println(rs.toString());
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I am unable to connect and receiving this exception
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "us-central1:test-instance"'.
Any help is highly appreciated.
Thanks!

Thanks nbk for your comment. I was able to solve the issue by modifying the connection string and including this dependency in my maven project
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.15</version>
</dependency>
Updated connection string
"jdbc:mysql:///testing?cloudSqlInstance=project-name:us-central1:test-instance&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=username&password=password"

Related

Java connection to a SQL Server Login failed for user

I want to connect to sql server 2017
I try without error to connect to sql server using sql server management studio
and I execute some query like :
SELECT fullname
FROM [AssetInst.Integ].[dbo].[Employee]
my problem now is to connect using java hibernate.
I use sqljdbc4.jar and jdk 1.6
first I try with this java class to test connexion:
public static void main(String[] args)
{
try
{
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
Connection con = DriverManager.getConnection("jdbc:sqlserver://192.168.0.12\\MSSQLSERVER2017:1433;databaseName=AssetInst.Integ","Test_user","P#ssw0rd123#");
String query =" select * FROM [AssetInst.Integ].[dbo].[Employee]";
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next())
{
System.out.print("fullname: " + resultSet.getString("fullname"));
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
but I have this error :
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'Test_user'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2529)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1905)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1893)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1045)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.dq.hibernate.generator.Snippet.main(Snippet.java:27)
this is work for me
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connectionMsSQl = DriverManager.getConnection(jdbc:sqlserver:/192.168.0.12;instanceName=AssetInst.Integ, "Test_user", "P#ssw0rd123#");
check name and password. try this one hope its works for you

Error When Trying Run SQL Server Query through Netbeans

My application is building successfully but won't run the query. Here's what I've done so far:
Downloaded JDBC Driver and used to successfully create connection to database, which is showing in services tab
Added CLASSPATH variable and added C:\Program Files\Java\jre1.8.0_221\bin;C:\Program Files\Java\jdk1.8.0_221\bin;.;C:\Program Files\Java\Microsoft JDBC Driver 7.4 for SQL Server\sqljdbc_7.4\enu\mssql-jdbc-7.4.1.jre8.jar as well as my JRE and JDK bin folders and .
Run below code
import java.sql.*;
public class TestCode {
public static void main(String[] args)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://mysqlserver:1433;databaseName=mydatabase;integratedSecurity=false;";
Connection conn = DriverManager.getConnection(url, "username", "password") ;
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT TOP 10 UserID FROM dbo.Users");
while (rs.next())
{
String userID = rs.getString("UserID");
System.out.println(userID);
}
}
catch (Exception e)
{
System.err.println("Error");
System.err.println(e.getMessage());
}
}
}
The error I'm getting is:
Error
com.microsoft.sqlserver.jdbc.SQLServerDriver
Which is the just the name of my driver. I got this from right clicking on the driver, clicking customize and copying the Driver Class from this Window.
Fixed.
Needed to add JDBC driver file to project library

NoSuchMethodError while connecting to Hive using Java JDBC

I am trying to connect to hive server using java.
I am runnig the code in Eclipse Oxygen and has Java 8 installed.
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException
{
try
{
Class.forName(driverName);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive2://<IP>:port/database", "username", "password");
Statement stmt = con.createStatement();
String sql = "show tables";
stmt.executeQuery(sql);
}
These are the external libraries I am using.
commons-logging-1.2
curator-client-2.0.0-incubating
hadoop-common-3.1.0
hive-exec-3.0.0
hive-jdbc-3.0.0
hive-metastore-3.0.0
hive-service-3.0.0
hive-service-rpc-2.1.0
httpclient-4.5.6
httpcore-4.4.10
libfb303-0.9.3
libthrift-0.9.3
log4j-1.2.17
slf4j-api-1.8.0-beta2
When I run the code I am getting the following error.
java.lang.NoSuchMethodError: org.apache.hive.service.auth.HiveAuthFactory.getSocketTransport(Ljava/lang/String;II)Lorg/apache/thrift/transport/TTransport
I can't figure out what is causing the error. I tried different versions of jars. Am I missing any library? Please help me.

Creating a java program which getting SQLite data and Insert in Oracle DB

I've just started my adventure with programming in SQL using JAVA.
I have Linux and Oracle Database on VirtualBox Machine.
My project is about situation, when a client give me a SQLite3 Database and I have to convert it to Oracle Database.
I've read some code but it gives error
Code:
CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "Move" AS
import java.sql.*;
import java.io.*;
public class getting {
public static void doIt() throws Exception{
Connection conn;
ResultSet rs;
Statement stat;
try{
Class.forName("org.sqlite.JDBC");
conn =
DriverManager.getConnection("jdbc:sqlite://127.0.0.1/media/sf_SHARE/baza.db");
} catch (SQLException e){
throw new RuntimeException(e);
}
try{
stat = conn.createStatement();
try{
rs = stat.executeQuery("SELECT * from entities");
while(rs.next()){
String w1= rs.getString("ID");
String w2 = rs.getString("TEXT");
System.out.println(w1+w2);
}
}finally{}
}finally{}
{try {rs.close();
}catch (Exception ignore){}
try {conn.close();
}catch (Exception ignore){}
try {stat.close();
}catch (Exception ignore){}
}
}
}
/
create or replace function Move return varchar2 as
language java name 'getting.doIt() return java.language.String';
/
select Move from dual;
I've got a error:
java.lang.ClassNotFoundException: org/sqlite/JDBC
Is connection in DriverManager.getConnection() is good?
Any ideas what I did wrong?
Cheers
najdzion
You have to download JDBC driver from here: https://bitbucket.org/xerial/sqlite-jdbc/downloads and import downloaded JAR to your project.
Also, as good practice, don't store connections as hard-coded strings.
If you are using maven, check your dependencies:
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.8.11.2</version>
</dependency>
Add your jar co Classpath:
> javac Example.java
> java -classpath ".;sqlite-jdbc-(VERSION).jar" Example # in Windows
or
> java -classpath ".:sqlite-jdbc-(VERSION).jar" Example # in Mac or Linux
or you can do it via your IDE.

Java database connection issue

I have the following issue with my code :
import java.sql.*;
public class App {
public static void main(String[] args){
String url = "jdbc:mysql://localhost:3306" ;
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{ System.out.println("Eroare incarcare driver!\n" + e);
return;
}
try{
Connection con = DriverManager.getConnection(url);
// Golim tabelul persoane
String sql = "DELETE FROM persoane";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
stmt.execute("CREATE DATABASE IF NOT EXISTS test");
stmt.execute("USE test");
i get the exception...any idea how i can make this work? thx.
enter code here
You need to download and add the jdbc connector to your classpath.
http://dev.mysql.com/downloads/connector/j/
java.lang.ClassNotFoundException occured due to "class not found" in your project/war/ear. Exception is very self explanatory, How to solve it.
In your case:
Add com.mysql.jdbc.Driver driver class/jar in your build/deployment/lib path you can
download it HERE
Read here
Offical
Make sure you have the MySQL driver on your application classpath.
Change
Connection con = DriverManager.getConnection(url);
to
Connection con = DriverManager.getConnection(url,"username","password");
and replace it with yourusername and password

Categories