I'm trying to connect to my database using sqljdbc4, I'm pretty new to this so i followed a couple of tutorial but it still doesn't seem to work, When i try to run the program i get this Exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''. ClientConnectionId:f181fd37-7e28-4392-ac86-02914c2090e1
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
And this is my code:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
You are not passing any authentication credentials. If you want to use integrated security (windows authentication), then you need to explicitly specify that in your connection URL and you need to load the native library required for this.
See Connecting with Integrated Authentication On Windows on Windows on MSDN.
This essentially comes down to including the folder containing the (32 bit or 64 bit) sqljdbc_auth.dll in the java.library.path system property (see link for details) and adding integratedSecurity=true to your connection string:
DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=DBank;integratedSecurity=true");
You are passing empty username and password while connecting to the database in getConnection method:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
Try supplying the db username and password, for example:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","myusername","mypassword");
Related
I am creating an application where you can manage an mySql database, at first i want the user to connect to the host by suppling the hostname, username and password. here is my code:
try {
Class.forName(ServerConnect.JDBC_DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Cannot register JDBC Driver...");
}
try {
conn = DriverManager.getConnection("jdbc:mysql://"
+ toServer.getHostname() + "/hrmanagement?" + "user=" + toServer.getUsername()
+ "&password=" + toServer.getPassword());
System.out.println("Connected to the server!");
} catch (SQLException e) {
System.out
.println("Not Connected to the server. Make sure username or password is correct!");
}
my question is, how can i connect without specifying the database so that i can let my user choose which database can he connect to. i tried removing "/hrmanagement?" but it didn't connect to the server. what can i do?
From the documentation:
The JDBC URL format for MySQL Connector/J is as follows, with items in square brackets ([, ]) being optional:
jdbc:mysql://[host][,failoverhost...][:port]/[database] ยป
[?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
So, remove hrmanagement, note that the / and ?user... parts are staying
my question is, how can i connect without specifying the database so
that i can let my user choose which database can he connect to. i
tried removing "/hrmanagement?" but it didn't connect to the server.
what can i do?
Move the question mark to "?user=". I think the other answer had this correct.
In terms of changing databases, I believe you can use setCatalog() to use a different database.
From the Connection Page:
void setCatalog(String catalog)
throws SQLException
Sets the given catalog name in order to select a subspace of this
Connection object's database in which to work.
If the driver does not support catalogs, it will silently ignore this
request.
Calling setCatalog has no effect on previously created or prepared
Statement objects. It is implementation defined whether a DBMS prepare
operation takes place immediately when the Connection method
prepareStatement or prepareCall is invoked. For maximum portability,
setCatalog should be called before a Statement is created or prepared.
Parameters:
catalog - the name of a catalog (subspace in this Connection object's database) in which to work Throws:
SQLException - if a database access error occurs or this method is called on a closed connection See Also:
getCatalog()
It would probably be easier to use this version of the call, a little less confusing
public static Connection getConnection(String url,
String user,
String password)
throws SQLException
So your code would look like
try {
conn = DriverManager.getConnection("jdbc:mysql://" + toServer.getHostname(),
toServer.getUsername(),
toServer.getPassword());
conn.setCatalog("someDifferentDB");
System.out.println("Connected to the server!");
} catch (SQLException e) {
System.out.println(e.toString());
}
As a side note, getConnection will attempt to load the JDBC driver for you, so you don't really need to whole Class.forName try/catch block. That's a vestige of old code that's not needed for most of the modern JDBC drivers. There's still some around that need it, but I believe mysql conforms to the newer style. Just make sure the driver is in your classpath on the command line
java -cp \path\to\mysql\driver\driver.jar myProgram
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
So I was just wondering, what (and probably, how much...) have I done wrong here with this code?
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
As I've triple-checked the username/password, I'm guessing it's something wrong with the host name. The database is only on the server (I don't have any kind of saved local version or anything...do I need to?).
And also, can someone just tell me if I'm on the right lines for what I want to do? Basically I've created a piece of software with a free version and a very cheap paid version. I was thinking that to prevent piracy, since the program requires internet connection anyway, I could store their email address as the username, then their computer's MAC address would be the password (each time the program was run, I would compare the MAC address on their PC with the one registered along with their email in the database. I've got no idea whether that is a good anti-piracy measure, but I was just wondering, if I manage to get the connection working, is that something that I'd be able to do or would there be e.g. security issues with that?
Anyway, thanks in advance :)
if it is not localhost i cannot comment on the host but you also have to give port number.It is missing.
Connection con = DriverManager
.getConnection("jdbc:mysql://"+pHost+":"+pPort+"/Your_mysql_schema_name",username, password);
and also in MYSQL your schema name would be your database name.Ensure that you are giving schema name and also port number.Usually for MYSQL its 3306
Writing a piece of java code to operate your database from a remote connection is not a good idea. Someone could reverse engineer your code and change your data.
You should atleast Implement an simple service on the net that could handle the spam you might receive, and protect your data.
I Think you missed the database port no in your URL .Try this :
try {
Class.forName("com.mysql.jdbc.Driver"); // Not Required for JDBC 4.0 onwards
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com: 3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Try instead of mysql1.000webhost.com to change with server IP address.
Example,
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://123.456.789.012:3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
I would recommend you some reading first. This slide show might present you how Java EE applications are build.
Next you might want to read a bit more how to connect your application with a database.
Hibernate is one of the most widely used tools for establishing connection between database and your Java program. It allows you to separate your connection data (e.g. username, password, connection url) from your code with use of configuration files in xml format. The line:
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
Is a very dangerous way of establishing connetion, as you are providing confidential credentials inside the code. There are ways to retreive this information from binary files.
You also asked, if is it worth having some local version of your database. The anwser is: Yes. Having your database locally might significantly speed up the time required for development and testing. It also allows you to work on your code even when no internet connection is available.
Providing authentication with use of MAC address is a very dangerous idea. Those addresses are attached to given machines. In other words the user will be able to connect to your application only with machine, on which he or she created an account. When using other computer (e.g. laptop at work) authentication will be denied.
I am trying to connect to Oracle DB hosted by the faculty.
Given information:
host: bazi.finki.ukim.mk
port: 1521
sid: ORCL
user: xxx
pass: xxx
here is the code:
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection c = DriverManager.getConnection("jdbc:oracle:thin:#bazi.finki.ukim.mk:1521:ORCL","user","pass");
}
catch (Exception e) {
System.out.println(e.getMessage());
}
I get "IO Error: The Network Adapter could not establish the connection"
Also i want to mention that, every group (by the way, this is for project) have workspace... also protected with username and password, even if I can connect into the database, how can i connect to the workspace?
...And also, they wrote that there need to be created tunnel with Putty, is that necessary and how to create it?
This is from http://www.orafaq.com/wiki/JDBC
There are 2 URL syntax, old syntax which will only work with SID and the new one with Oracle service name.
Old syntax
jdbc:oracle:thin:#[HOST][:PORT]:SID
New syntax
jdbc:oracle:thin:#//[HOST][:PORT]/SERVICE
Also note that these 2 lines are unnecessary
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
DriverManager will automatically detect the necessary driver by url, see API
I'm a java beginner and I'm working on a simple application which connects to a remote mysql database using JDBC. I've tested it locally and it works just fine, however I cannot get it to work on for my remote server.
I don't think its of much use but heres the code:
Connection connection = null;
String dburl = "jdbc:mysql://314159265:3306/Db_Name";
String userName = "user";
String passWord = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dburl, userName, passWord);
Statement st = connection.createStatement();
String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
int rsI = st.executeUpdate(query);
System.out.println("Hi");
}catch (Exception e) {
System.out.println(e);
} finally {
if (connection != null) {
try {
connection.close();
System.out.println("Database connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
When I run this, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.The driver has not received any packets from the server.
I'm pretty sure it must be some kind of server configuration issue.
Notes:
Username, password, IP, database name, etc. are just examples.
This could be a firewall problem, or a configuration problem. But I don't think it is a coding problem at all - you need to start troubleshooting the connection.
Trouble shoot by attempting to use third party client apps to connect to mysql. This will indicate whether it is configured for external access. Although it doesn't ensure that JDBC is visible from the outside, it does rule out some potential firewall problems.
Follow this guide to help you mess with your configurations
Remote MYSQL Database Access
If you are still stuck, it could be a coding problem so check out this page:
How to connent to a remote mysql database with java?
P.S. I am assuming you are using unix as the operating system.
I guess 314159265 could be replaced by some address....
like jdbc:mysql://localhost:3306/
or jdbc:mysql://127.0.0.1:3306/
I ve installed MySQL (last update).
I need to code, that ll create & establish a connection with SQL DB
& manage the DB(using SELECT, INSERT, CREATE).
I did everything but, I am not able to create connection. I've also installed the MySQL/J connector, I just extracted the .zip pack in a folder & added the folder path in Variables).
Can anyone tell me wat is meant by URL in the below line?
Connection connection = DriverManager.getConnection(url, username, password);
I ve tried this:
String url = "jdbc:odbc:sqlserver://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
But it's not working. I am unable able to understand the term 'URL'.
Can anyone explain, the meaning of 'url' and wat should be done to connect to a SQL server from Java.
Update:
This is the Full code. It still cannot connect.
import java.sql.*;
public class TestDriver {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//This s wat actually i did for connection
System.out.println("Driver Loaded Succesfully");
}
catch (Exception e){
System.out.println("Unable to Load Driver!!!");
}
try {
Class.forName(com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
Connection con = DriverManager.getConnection(url, "root", "1234");
System.out.println("connection Established");
}
catch(Exception e) {
System.out.println("Couldnt get connection");
}
}
}
Can you tell me wat is the purpose of MySQL Connector/J?
In the question you seem to be using a MySQL jdbc driver with a SQL Server jdbc URL. This won't work.
If you are using a MySQL database:
Class.forName("com.mysql.jdbc.Driver"); // initialise the driver
String url ="jdbc:mysql://localhost:3306/myfirstdb";
If you are using a SQL Server database you are going to need a completely different jdbc driver. jTDS is open source and a good option. Include the jtds.jar file in your classpath and use something like:
Class.forName("net.sourceforge.jtds.jdbc.Driver"); // initialise the driver
String url = "jdbc:jtds:sqlserver://localhost:1433/myfirstdb";
Here's an extract from your code:
} catch (Exception e) {
System.out.println("Couldnt get connection");
}
You should never suppress exceptions as long as you don't understand its cause. Replace it by at least:
} catch (Exception e) {
System.out.println("Could not get connection");
e.printStackTrace();
}
Or maybe
} catch (Exception e) {
throw new RuntimeException("Could not get connection", e);
}
Either way, you should see the exception type, message and trace. In your code snippet the possible exceptions are ClassNotFoundException and SQLException. The first one would mean that the driver is not properly placed in the classpath. The second one would mean that connection cannot be obtained. The exception message and/or trace should tell in detail about the underlying root cause of the problem.
You should always observe exceptions. They tell something about the cause of the problem. You know, once a cause is understood, the solution is nothing more than obvious :)
See also:
Short MySQL/JDBC tutorial - Contains explanation about exception causes.
Further,
Can anyone tell me wat is meant by URL in the below line?
An URL is an Uniform Resource Locator. It's a common way to locate (identify) unique resources in computer systems and networks. The URL syntax for the MySQL database is explained in the documentation of the JDBC driver.
Can you tell me wat is the purpose of MySQL Connector/J?
It's the JDBC driver. The JDBC API exist of almost only interfaces. The DB vendors should provide their own concrete JDBC API implementation, which is the JDBC driver. With a JDBC driver you'll be able to connect a specific database using JDBC API.
If its MS SQL Server,
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
For more info, see this to get started with Microsoft JDBC.
You can use any of the two JDBC drivers for MSSQL:
Microsoft SQL Server JDBC Driver
2.0
jTDS
For MS SQL Server driver 2.0, use
URL: jdbc:sqlserver://server:port; DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
For MySql & Java, see this on SO.
You forgot a " at Class.forName(com.mysql.jdbc.Driver");
It should be
Class.forName("com.mysql.jdbc.Driver");