Connecting to sybase using jdbc in solaris - java

I am trying to learn how to use jdbc.
Normally to connect to sybase db on solaris I use:
isql -Usa -Pxxxxxx -Dxxxxxx
its gets connected to the db by the above.and i can rightaway execute the queries.
Now i am trying to just do a similar thing using java.
below is my code.
public class SKRSample
{
public static void main(String args[])
{
try
{
Class.forName("com.sybase.jdbc.SybDriver");
}
catch (ClassNotFoundException cnfe)
{
System.err.println("Error loading driver: " + cnfe);
}
try
{
String host = "172.16.65.33";
String dbName = "bsmdb";
int port = 1234;
String url = "jdbc:sybase:Tds:" + host + ":" + port + ":" + "?SERVICENAME=" + dbName;
for (int n = 0; n<args.length; n++) {
if (args[n].equals("-u")) user = args[++n];
else if (args[n].equals("-p")) password = args[++n];
else throw new IllegalArgumentException("Unknown argument.");
}
Connection con = DriverManager.getConnection(url, user, password);//here is the error.
The last line of the code is where there is a runtime error.
i compiled the code and execueted as below:
setenv LOGIN "sa"
setenv PASSWORD "xxxxxxx"
javac SKRSample.java
java SKRSample -u $LOGIN -p $PASSWORD
the error i am getting is :
Unexpected exception : java.sql.SQLException: No suitable driver found for jdbc:sybase:Tds:172.16.65.33:1234:?SERVICENAME=bsmdb, sqlstate = 08001
i have a doubt that either the host is incorrect or the port is incorrect or the url i am framing is incorrect.how can get the host name if at all it is incorrect.and also how can get the port number if the problem lies there.
But i am not sure about the problem.Can anyone give me some head's up regarding where exactly the problem is there.

Seems that the JDBC url format is wrong.
the right format is jdbc:jtds:sybase://<host>[:<port>][/<database_name>]

You will have to download the driver and execute the class so that it uses the driver in the path specified by you.

You need to use proper JDBC driver and connection string together. For example, you can use "com.sybase.jdbc2.jdbc.SybDriver" (in jconn2.jar) and "jdbc:sybase:Tds:MyDbComputerNameOrIP:2638" together. Please check the following page for more options.
Sybase JDBC Driver and URL Information
In your code, it seems that you added extra ":" in the connection URL. Remote the ":" after port number. The following two connection URL should work with "com.sybase.jdbc.SybDriver".
String url = "jdbc:sybase:Tds:" + host + ":" + port + "?SERVICENAME=" + dbName;
or
String url = "jdbc:sybase:Tds:" + host + ":" + port + "/" + dbName;

Class.forName("net.sourceforge.jtds.jdbc.Driver");
And use JTDS driver jar in the classpath

It may be a bit late, but still I had the same issue and spent much time investigating, so I'll put some outcome here:
1. We need to include the driver class in our code as well as java.sql:
import com.sybase.jdbc3.jdbc.SybDriver;
import java.sql.*;
2. We need to run javac with the path to the driver in the classpath (I have jconn3.jar here - /usr/local/localagent/jar/jconn3.jar):
javac -cp "/usr/local/localagent/jar/*" test_conn.java
3. We need to put the same classpath when running the class:
java -cp ".:/usr/local/localagent/jar/*" test_conn
My code for test_conn.java is below:
import com.sybase.jdbc3.jdbc.SybDriver;
import java.sql.*;
public class test_conn {
public static void main(String[] args) {
String host = "myhost";
String url = "jdbc:sybase:Tds:"+host+":4100";
String username = "username";
String password ="password";
String dbname ="dbname";
SybDriver sybDriver = null;
Connection conn;
try
{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
System.out.println("Driver Loaded");
conn = DriverManager.getConnection( "jdbc:sybase:Tds:"+host+":4100?SERVICENAME="+dbname, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("sp_helpdb");
rs.next();
System.out.println(rs.getString(1));
conn.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
}
It worked for me, so I hope this helps.

Related

Issues with username and password when connecting to oracle database 12c through ojdbc

I have SQL developer installed and a properly configured DB, I create a user from sys like so:
CREATE USER random IDENTIFIED BY 12345;
GRANT ALL PRIVILEGES TO random;
I attempt to connect to the oracle SQL database with the ojdbc8.jar found in oracles website like this:
String url = "jdbc:oracle:thin:random/12345#localhost:1521:home";
try{
Connection dbConn = DriverManager.getConnection(url);
}catch(Exception e){
System.out.println("Exception: " + e.getLocalizedMessage());
}
However I receive this error:
Exception: ORA-01017: invalid username/password; logon denied
The last time I asked this question it was just populated by answers that have no actual answer to the problem at hand, I don't need to change the driver to a different one, I don't need to instantiate some sort of factory nonsense that just adds complexity, all I want to know is how I'm meant to connect to an account that is part of my DB so I can perform basic SQL functions.
Edit:
It just occurred to me that it is a pdb, is there a modification needed to the connection url that anyone can point out?
Try:
Connection dbConn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:home", "random", "12345");
PDB connections need a slight tweak.
Please use localhost:port/sid instead of localhost:port:sid:
if (isPluggableDB) {
conn = DriverManager.getConnection("jdbc:oracle:thin:#" + hostName + ":" + hostPort + "/" + sid, userName, password);
} else {
conn = DriverManager.getConnection("jdbc:oracle:thin:#" + hostName + ":" + hostPort + ":" + sid, userName, password);
}

Java Connection String to Oracle Cloud Database

I had problem when connecting to Oracle Cloud Database from java code.
I have no problem connecting other non-cloud oracle databases.
I can connect to the Oracle Cloud Database with sql tools, except from the java codes.
The hostname, username and password is correct one, i don't reveal the real username and password.
Error: java.sql.SQLException:
SQLException: SQLState(null) vendor code(17002)
java.sql.SQLException: Io exception: Oracle Error ORA-12650: No common encryption or data integrity algorithm
My code as following:
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521:ORCL";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(dbURL, "username1", "password");
}catch(Exception)
{
e.printStacktrace();
}
/**
* The below one is for oracle thin client
Its worked for the ojdbc6 driver.
*/
public Connection conCheck() {
Connection con=null;
try { //step1 load the driver class
Class.forName("oracle.jdbc.OracleDriver");
Properties props = new Properties();
props.put("oracle.net.encryption_client", "REQUIRED");
props.put("oracle.net.encryption_types_client", "( " + AnoServices.ENCRYPTION_AES256 + "," +AnoServices.ENCRYPTION_AES192 + ")");
props.put("oracle.net.crypto_checksum_types_client", "( SHA1 )");
props.put("user", "username");
props.put("password","password");
//step2 create the connection object
con=DriverManager.getConnection( "jdbc:oracle:thin:#host:port:serveiceid",props);
System.out.println("Con"+con);
}catch(Exception e) {e.printStackTrace(); }
return con;
}
Seems like changing syntax in your connection string to lookup SERVICE_NAME instead of SID must help you connect your database.
String dbURL = "jdbc:oracle:thin:#192.133.133.23:1521/ORCL";
Additional Read : Thin-style Service Name Syntax
If this as well doesn't help, then would suggest to add below 2 lines to your sqlnet.ora in database.
SQLNET.CRYPTO_CHECKSUM_TYPES_CLIENT= (SHA1)
SQLNET.CRYPTO_CHECKSUM_CLIENT = requested
First mandatory check is to verify the oracle jdbc version. if you use incompatible version,we will get this kid of errors.

How to specify path to mySQL using localhost?

I have been having issues specifying the path (I have two files: comments.frm and db.opt in the following folder: C:\xampp\mysql\data\feedback)... I am using XAMPP and mySQL. I am not sure why I am having an error? Please, take a look this part of my code:
public void readDataBase() throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager
.getConnection("jdbc:mysql://localhost//feedback"
+ "user=root&password=1234");
PS: My password for localhost is 12345678
You should try
DriverManager.getConnection("jdbc:mysql://localhost/feedback", "root", "1234");
For better clarity you can use the other overloaded method while getting connection.
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://<db_ip>/<db_name>",
"<username>", "<pwd>");
Try
connect = DriverManager
.getConnection("jdbc:mysql://localhost/feedback?user=root&password=1234")
(you forgot about the question mark after "feedback")
Many answers but everyone forgot the port of the database.
If you use mysql then try 3306 as db port.
http://www.petefreitag.com/articles/jdbc_urls/ - list of jdbc urls (Examples)
try
{
conn = DriverManager.getConnection("jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName, user, passwd);
}
catch(SQLException sqle)
{
System.out.println("Connection fails: " + sqle.getMessage());
}
I think you need to use this:
DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback", "root", "1234");
I check my old project and find that I don't use double slash here /feedback.
also you can specify encoding like this :
DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback?characterEncoding=UTF-8&characterEncoding=Cp1251", "root", "1234");
and also one more advice. Don't use hard code. Get url, password and user name from property files.
Try this hope it can help you!!!
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/feedback?"+"user=root&password=1234");
also see the URL Mistakes like:
jdbc:mysql://localhost//feedback?
// after localhost... check and try my code...
.

Why am I receiving this SQLException error stating that no suitable driver can be found?

I'm on a mac, running a MAMP instance of MySQL. I'm trying to use a jdbc driver to connect my java code to a database called 'test', working with a table called 'customer.' I keep getting an error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:8889/test
I'm not sure if the problem is with my code, or if it's a configuration problem with the MAMP instance of MySQL, or if it's something else entirely.
I have an initialize driver method:
public void initializeDriver(){
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.err.println(e.toString());
}
}
And I have a connection created in the following way:
public void insertCustomer(String connectionUrl, String connectionUser, String connectionPassword, Customer customer) {
try{
Connection conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
Statement constat = conn.createStatement();
String query = "INSERT INTO customers (customer_id, email, deliverable, create_date) VALUES (" + customer.id + ", " + customer.emailAddress + ", " + customer.deliverable + ", " + customer.createDate + ")" ;
constat.executeQuery(query);
conn.close();
}
catch(SQLException e){
System.out.println(e.toString());
}
}
And I have downloaded mysql-connector-java-5.1.20 and set it in my classpath.
If anyone has any suggestions for how I could correct this error, I would be really grateful!
You have to put MySQL jdbc connector jar library into the classpath.
Then initialize the driver before opening the connection with code like the following :
Class.forName("com.mysql.jdbc.Driver").newInstance();
You will need the corresponding mysql JDBC driver jar in your classpath or loadable by your container. See the doc for ConnectorJ and note the installation instructions.
Try to add mysql-connector-java-5.1.20.jar to Glassfish (or Tomcat) lib folder.
you have also a error in this row
constat.executeQuery(query);
if you want insert some data in data base you have to use this code
constat.executeUpdate(query);

Access Denied? Wrong user / pass

I'm trying to write a java program to connect to the same MySQL database my website uses. I am using the same login details, minus the hostname ofcourse, but I am getting these errors:
SQLException: Access denied for user 'USER'#'HOSTNAME' (using password: YES)
SQLState: 28000
VendorError: 1045
I am using the hostname my host provided, and the password and user are the same details I have on my website.
Here is the code snippit:
public main() {
Connection con = null;
String mysql_hostname = "HOST";
String mysql_username = "USER";
String mysql_password = "PASS";
String mysql_database = "DB";
int mysql_port = 3306;
initComponents();
try {
con = DriverManager.getConnection("jdbc:mysql://"+ mysql_hostname +":"+ mysql_port +"/"+ mysql_database +"?user="+ mysql_username +"&password="+ mysql_password);
}
catch(SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
This is probably to do with some cPanel settings, but I am very new to Java, so asking couldn't hurt...right? :D
On cPanel as I remember when you create a db user there is also a hostname associated with that user default (localhost), If you are running your code on local machine you have to add your IP (public IP) or % in hostname for this db user from cPanel. So mysql will allow connection from your machine.
Note: adding % is risky, make sure you have a strong password.

Categories

Resources