I can't connect to sql anywhere 16 database - java

I have been try to connect with a sql anywhere (v. 16) but what i get is
(java.sql.SQLException: [Sybase][JDBC Driver][SQL Anywhere]Database server not found) error.
This is my code:
public class DBConnection {
private LoginGUI loginGUI;
protected Connection conn;
String dbName = "CPO";
public DBConnection(LoginGUI loginGUI) {
this.loginGUI=loginGUI;
String user = loginGUI.getUsernameStr();
String passwd = loginGUI.getPasswordStr();
String dbUrl = "jdbc:sqlanywhere:uid=" + user + ";pwd=" + passwd + ";eng=demo";
try {
conn = DriverManager.getConnection (dbUrl);
loginGUI.getLoginFrame().setVisible(false);
GUI gui = new GUI();
} catch (SQLException e) {
System.err.println("Can't connect to database");
System.err.println("(" + e + ")\n");
}
}
public Connection connection() {
return this.conn;
}
}

If you're using the JDBC driver for SQL Anywhere 16, you need to change it to the following:
jdbc:sybase:Tds:[server-ip]:[port]/[dbName]
See SAP's documentation about this.
Alternatively you might check out the open source JDBC driver jtds that supports SQL Anywhere as well. In that case the connection string would be
jdbc:jtds:sybase://[server-ip]:[port]/[dbName]

Related

Access is Denied, Issue in embedded Derby

I'm having a problem with my derby engine.
When I make a new database , create new tables and insert or display rows , everything works fine. And when I try to use the database in my practice example , the database works fine and I'm able to insert and select data from the table.
Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Restaurants
{
private static String dbURL = "jdbc:derby:c:\\Apache\\db-derby-10.14.2.0-bin\\bin\\myDBExample;create=true";
private static String tableName = "restaurants";
// jdbc Connection
private static Connection conn = null;
private static Statement stmt = null;
public static void main(String[] args)
{
createConnection();
//insertRestaurants(5, "LaVals Leb", "Berkeley");
//insertRestaurants(6, "House Leb", "New York");
selectRestaurants();
shutdown();
}
private static void createConnection()
{
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
conn = DriverManager.getConnection(dbURL);
}
catch (Exception except)
{
except.printStackTrace();
}
}
private static void insertRestaurants(int id, String restName, String cityName)
{
try
{
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (" +
id + ",'" + restName + "','" + cityName +"')");
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void selectRestaurants()
{
try
{
stmt = conn.createStatement();
ResultSet results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
int numberCols = rsmd.getColumnCount();
for (int i=1; i<=numberCols; i++)
{
//print Column Names
System.out.print(rsmd.getColumnLabel(i)+"\t\t");
}
System.out.println("\n-------------------------------------------------");
while(results.next())
{
int id = results.getInt(1);
String restName = results.getString(2);
String cityName = results.getString(3);
System.out.println(id + "\t\t" + restName + "\t\t" + cityName);
}
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
private static void shutdown()
{
try
{
if (stmt != null)
{
stmt.close();
}
if (conn != null)
{
DriverManager.getConnection(dbURL + ";shutdown=true");
conn.close();
}
}
catch (SQLException sqlExcept)
{
}
}
}
This code works fine but when I try to create a connection to the same database again with ij , I get an error in my command prompt like this:
In the image, the upper part is when I first make my database but after that when I use it in eclipse, it gives me this error. Even using a db in eclipse once will result in this error.
What is the issue? Why is derby engine not getting the access granted to it?
Any help is appreciated.
I suspect that you confused the database modes here. In your question's title you mention "embedded Derby", but you're code is using the ClientDriver and the create=true attribute, which does create the DB if it doesn't exist, but it doesn't start the server.
If you don't want to start the server, you can just use the EmbeddedDriver.
Another point where you might run into problems is with the shutdown=true attribute. You're using the entire DB URL (dbURL) including the filename, but if you want to shut down the server from your code, you should omit the filename, like this : jdbc:derby:;shutdown=true.
You can check out the Derby developer docs for information on using these attributes, and the Embedded Derby tutorial for using Derby in embedded mode, sou you won't have to worry about starting the server.
Found out the issue. I had to start the derby as a network server on the port by using the following command:
startNetworkServer.bat

Connect SQL Server database from Java

I need to Connect the SQL Server 2008 from the Java.
Here is my code:
public class Sql {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
public static void main(String[] args){
// Neue DB und los geht's :)
DB db = new DB();
db.dbConnect("jdbc:sqlserver://Data Source=500.20.13.1;InitialCatalog=LicenceManagement;UseID=XXXXX;Password=YYYY");
}
}
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();
}
}
};
But the connection isn't established, and I get the following error:
ERR :No suitable driver found for jdbc:sqlserver://Data
Source=500.20.13.1;InitialCatalog=LicenceManagement;UseID=XXXXX;Password=YYYY"
Have a look here for jdbc Driver for MSSQL:
https://learn.microsoft.com/en-us/sql/connect/jdbc/microsoft-jdbc-driver-for-sql-server?view=sql-server-2017
first of all you have to find a driver like #Benedikt Geltenpoth said above (or below).
Secondly include your driver in your classpath, after you've download it.
Third From Java 1.6 upward, you dont need to register the driver class anymore
see (in theorie) here. the driver is JDBC type 4
Lastly A simple pattern for your connection would be jdbc:sqlserver://server:port;DatabaseName=dbname plus your url parameters
public class Sql {
public static void main(String[] args){
// Neue DB und los geht's :)
DB db = new DB();
int yourPort = 1433;
String initialCatalog = "LicenceManagement";
String userId = "userOne";
String password= "passwordOne";
db.dbConnect("jdbc:sqlserver://"+500.20.13.1+":"+yourPort+";DatabaseName="+initialCatalog,userId,password);
}
}
class DB{
public void dbConnect( String db_connect_string,
String db_userid,
String db_password){
try{
Connection conn = DriverManager.getConnection(
db_connect_string,
db_userid,
db_password);
System.out.println( "connected" );
}
catch( SQLException e ){
e.printStackTrace();
}
}
};

Java access DataBase connection

I want to learn how to connect DB with java. I write following code for that:
package login;
import java.sql.*;
public class DBTest {
public static void main(String[] args) {
try {
Class.forName("sun.odbc.jdbc.JdbcOdbcDriver");
Connection c = DriverManager.getConnection("jdbc:odbc:Test");
Statement s = c.createStatement();
String sql = "select * from Table1";
ResultSet result = s.executeQuery(sql);
while (result.next()) {
System.out.println("\n" + result.getString(1) + "\t" + result.getString(2));
}
} catch (Exception e) {
System.out.println("exception generated:" + e.getMessage());
}
}
}
but I get exception:
run:
exception generated:sun.odbc.jdbc.JdbcOdbcDriver BUILD SUCCESSFUL
(total time: 0 seconds)
I cerated database named exp.accdb. How I get solve this problem?
Don't you have to put in the database credentials, i.e. the hostname, username and password?
For instance:
c = DriverManager.getConnection(host, username, password);
You can check if it is connected during debugging by doing this as well:
if (c != null) {
System.out.println("Connection established");
}

java access try code block from a separate class

Hi i am trying to use an Access data bases within java and i am having a spot of trouble. below i have set up a connection to my database.
public class DBAccess {
DBAccess() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=CFPDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
I need to access the 's' variable form with my gui class in order to check a password:
else if(event.getSource() == loginSubmitButton){
DBAccess loginCheck;
String selFromTable = "SELECT PASSWORD FROM USERS WHERE USERNAME = '" + loginUsername.getText() + "'; ";
loginCheck.s.execute(selFromTable);
ResultSet retrievedPassword = loginCheck.s.getResultSet();
String password = retrievedPassword.getString(1);
String password_entered = loginPassword.getText();
}
But my compiler says it can't find symbol - variable 's'.
Class DBAccess is in a separate file to my gui, but are both in the same package. any help would be great. :)
Java doesn't work like this, each variable has its own scope, indicating where is it defined, where is it prone to be used and when will be collected by Garbage Collector. In general, a good way to remember it at the begining is that variable will only 'live' while inside the nearest brackets {}.
In this case, your 's' variable has a limited scope for the try-catch block, so as soon as that block ends, the s variable is not accessible anymore, you can verify this by trying to compile this code:
DBAccess() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=CFPDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement();
s.execute(""); // compiles without problem.
}
catch(Exception ex) {
s.execute(""); // does not compile.
ex.printStackTrace();
}
s.execute(""); // does not compile.
}
So your best option is to declare s as a class field:
public class DBAccess {
private Statement s;
DBAccess() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=CFPDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
s = conn.createStatement();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public Statement getStatement() {
return s;
}
}
And then accessible it via it's getter method. By the way, remember to instantiate your object via its constructor (line 2)
else if(event.getSource() == loginSubmitButton){
DBAccess loginCheck = new DBAccess(); // invoke constructor
String selFromTable = "SELECT PASSWORD FROM USERS WHERE USERNAME = '" + loginUsername.getText() + "'; ";
loginCheck.getStatement().execute(selFromTable);
ResultSet retrievedPassword = loginCheck.getStatement().getResultSet();
String password = retrievedPassword.getString(1);
String password_entered = loginPassword.getText();
}
Another option which I don't really recommend (but state here just for you to know) is to declare the s field as public:
public class DBAccess {
public Statement s;
DBAccess() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=CFPDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
s = conn.createStatement();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
Then you can access it the way you wanted:
loginCheck.s.execute(selFromTable);
You need to make field from s, because field exists as long as object owning it exists. The s now disappears when DBAccess constructor finishes. So you want something like this:
public class DBAccess {
private Statement s;
DBAccess() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=CFPDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
s = conn.createStatement();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
public Statement getStatement() {
return s;
}
}
and in your gui class access the s using getter:
else if(event.getSource() == loginSubmitButton){
DBAccess loginCheck;
String selFromTable = "SELECT PASSWORD FROM USERS WHERE USERNAME = '" + loginUsername.getText() + "'; "; //this is vulnerable to SQL injection, use prepared statements, see for example, here https://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/
loginCheck.getStatement().execute(selFromTable);
ResultSet retrievedPassword = loginCheck.s.getResultSet();
String password = retrievedPassword.getString(1);
String password_entered = loginPassword.getText();
}

Blocked on connecting to Amazon RDS

I have recently deployed a DB Instance on Amazon RDS and I am trying to get the hang of it. After following the instructions on the documentation I tried connecting to that DB Instance but for some reason my simple program which shows the server's version hangs on the connection.
Here is my code:
import java.sql.*;
public class AWSTest {
public static void main(String[] args) {
System.out.println(getVersion());
}
public static String getVersion() {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println("Driver Error: " + e.getMessage());
return VERSION_NOT_FOUND;
}
System.out.println(CONNECTING_MESSAGE);
try (Connection con = DriverManager.getConnection(DB_URL,
USER,
PASS);
Statement stmt = con.createStatement();) {
System.out.println("Getting server version...");
try (ResultSet rs = stmt.executeQuery(VERSION_QUERY);) {
rs.next();
return rs.getString(1);
}
} catch (SQLException se) {
System.out.println("SQL Error: " + se.getErrorCode() + " "
+ se.getMessage());
return VERSION_NOT_FOUND;
}
}
static final String DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://**************.*******."
+ "*******.rds.amazonaws.com:3306";
private static final String VERSION_QUERY = "Select VERSION()";
static final String USER = "*******";
static final String PASS = "*******";
private static final String VERSION_NOT_FOUND = "Version was not found";
public static final String GETTING_DRIVER_MESSAGE = "Getting driver...";
public static final String CONNECTING_MESSAGE = "Connecting to server...";
}
My program hangs at the line Connection con = DriverManager.getConnection(DB_URL, USER, PASS); and my main problem is that it does not even throw an exception, it just stays there.
USER, PASS and DB_URL are definitely correct.
It sounds like your ip/port is getting blocked/dropped. That's typically the case when a connection does nothing (as opposed to getting refused or failed login). Make sure your Security Group is set up properly. http://aws.amazon.com/rds/faqs/#31

Categories