Java Connect To SqlServer Database - java

I am trying to connect to the SQL Server database using Eclipse but it's giving me the error:
Cannot open database "AdventureWorks2012" requested by the login. The login failed.

Since you are using integratedSecurity=true it means that you windows account is not allowed to access AdventureWorks2012 database. You need to grant the Windows account you are logged in (or running Eclipse) the database access rights. You can follow To configure database access docs to grant your Windows account access:
On the computer that is running SQL Server, start SQL Server Management Studio. In the Registered Servers pane, double-click SQL Server.
In the object explorer pane, expand SQL Server, expand the Security folder, right-click Logins, and then click New Login.
In the Login – New dialog box, specify either Windows Authentication or SQL Server Authentication mode.
If you are using Windows Authentication, enter a logon name and select either the Grant Access or the Deny Access option.
If you are using SQL Server Authentication, type a logon name and password, and then confirm the password.
In the left pane, click Database Access.
In the right pane, select the Permit check box for the databases you are granting access to, and then click OK.
If you want to connect by specifying username and password use integratedSecurity=false and supply username and password as shown in the Establishing a Connection docs:
String jdbcUrl = "jdbc:sqlserver:...";
Properties props = new Properties();
props.put("user", <database username>);
props.put("password", <database password>);
try (Connection conn = DriverManager.getConnection(jdbcUrl, props)) {
...
}

Related

Connecting to DB using JDBC driver with different user login

I have opened sql with other user (Shift+Right click and run as different user) by providing user name and password, hence when I connect to SQL Server, with windows authentication am able to access the DB's and tables.
Now, can I do this using Java? When I use below code:
conn = DriverManager.getConnection("jdbc:sqlserver://ServerName;Database=Testing;integratedSecurity=true");
Error:
Login failed for user so and so. This is actually correct because it is taking the login information of system I am currently using.
You can add to JDBC connection your new password and username
jdbc:sqlserver://localhost;user=MyUserName;password=*****;
So in your code:
DriverManager.getConnection("jdbc:sqlserver://ServerName;Database=Testing;integratedSecurity=true;user=MyUserName;password=*****");
Note
Although the previous example uses a username and password in the connection string, you should use integrated security as it is more secure. For more information, see the Connecting with Integrated Authentication section later in this topic.

MYSQL Connection: Access Denied

These are my codes for the database connection:
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection("jdbc:mysql://10.44.222.111/try?"
+ "user=jenny&password=perez");
After running the program, it display this error:
com.mysql.jdbc.exception.jdbc4.MySQLSyntaxErrorException:
Access denied for user 'jenny' # '%' to database 'try'
I am using MySQL Workbench.
Go to MySQL Workbench, then User Privileges, click your username, then check all Administrative Roles then click apply. This will allow connection for user 'jenny'.
As the error says, user 'jenny' does not have access to connect to database from any host(%). On mysql prompt, run the following command to provide privileges to user 'jenny' to connect from any host.
GRANT ALL PRIVILEGES ON try.* TO 'jenny'#'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
You may use specific PRIVILEGES instead of ALL as per your requirement.
This would indicate that your user does not have permission to access that database from any client host ('%').
MySQL uses a four part mechanism for allowing access:
username
password
database
client host
You need to make sure that the user is authorised in MySql to access the 'try' database and is allowed to connect from any client host ('%') and has the correct username and password.
Also, you should ensure you are connecting to port 3306 (unless MySQL is running on a non-standard port).

MySQL: Access denied for user 'userName'#'localhost'

I am having an issue with creating and grating permissions to a user using phpMyAdmin. I am having a Java swing application and it need to connect to this database.
How I created the user and granted the permission are below, step by step.
Open phpMyAdmin
Go to 'Users' tab.
Click on Add New User
Give the user name, select Any Host as the host (so the % is displayed in its text box), and mention the password. Any host is because remote access required.
Select Select under Global Privileges - Data
Click on Go
Now I am in the Users tab starting page again.
Click on Edit Privileges on my newly created user.
Select the database under Database-specific privileges
Tick everything under Database-specific privileges, Data section.
Click on Go
Now, whenever my Java application connects to this, it gives the below error
java.sql.SQLException: Access denied for user 'userName'#'localhost' (using password: YES)
This is how I connect to the database, in my Java application
con = DriverManager.getConnection("jdbc:mysql://"+ip+":3306/databaseName","user","password");
Here,for the variable ip, I tried both localhost and 127.0.0.1 but still no good. What have I done wrong?
I noticed the connection works fine if I select Localhost instead of Any Host in step 4.
After you have made your user.
Click edit priviliges.
Change Any Host for Localhost.
Apply your priviliges.
Scroll to the bottom and
make sure that "keep old one" is selected and press Go.
You need to grant permissions to the userName#localhost in mysql.
GRANT ALL PRIVILEGES ON database_name TO userName#localhost IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
sometimes, mysql server doesn't get a 'localhost' from a local connection, you should try :
GRANT ALL PRIVILEGES ON database_name TO 'userName'#'theHostName' IDENTIFIED BY 'password';
or in a more risky way:
GRANT ALL PRIVILEGES ON database_name TO 'userName'#'%' IDENTIFIED BY 'password';
and finally
FLUSH PRIVILEGES;
Have you set any password for the phpmyadmin. if yes please include that in the password field.or you can try lik this
con = DriverManager.getConnection("jdbc:mysql://"+ip+":3306/databaseName","localhost","");

Its trying to connect as DOMAIN/COMPUTERNAME instead of DOMAIN/USERNAME

Unable to connect with sql server with servlet.
its on tomcat 7 which says
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection ("jdbc:sqlserver://;integratedSecurity=true");
Getting error:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'MYDOMAIN\SUMIT-PC$'.
SUMIT-PC is my computer's name.
it should be 'MYDOMAIN\SUMIT SINGH'
This means that your tomcat is running under LocalSystem account in domain-based network. If you want to make tomcat to use your login propagation - you should to tune up it to impersonate logged on user and your tomcat and sql server(or workstation for windows 2003 domains) should be trusted for delegation on domain level, and user MYDOMAIN\SUMIT SINGH should be also not denied for delegation on domain level.
or
implement your own impersonation inside the server process - this requires you to know user's password
Today I got the same issue. In my machine, it was Tomcat 8.5 and I have installed tomcat as a windows service. (installed using apache-tomcat-8.5.40.exe)
Press the Win + R keys on your keyboard, to open the Run window. Then, type services.msc and hit Enter or press OK.
Right click on Tomcat service and select Properties. In that dialog box go to Log On tab and select This Account under Log on as option. Fill your username, password as well. Then click OK.
Then restart the service!!!

Connecting SQL Server 2008 to Java: Login failed for user error

I am trying to connect my Java code to a Microsoft SQL Server 2008 R2 Express database. I have downloaded the Microsoft SQL Server JDBC Driver 3.0 and added the sqljdbc4.jar to my classpath. I am using Netbeans and have included the sqljdbc4.jar in my project also.
I created a database in the SQL Server Management Studio called TestDB1 and added some columns and values that I will use for testing. I changed from Windows Authentication Mode by right clicking on the server JACOB=PC\SQLEXPRESS->Properties->Secuity and changing from Windows Authentication Mode to SQL Server and Windows Authentication Mode.
I then created a new login by right clicking on the Login folder in the window explorer under JACOB-PC/SQLEXPRESS->Secuity Folder->Logins Folder and added a new login. I gave it the name jhaip2, switched to SQL Server authentication and the set the password to jacob. Enforce password policy and enforce password expiration are unchecked. The default database is set to TestDB1. Then under TestDB1->Secuity->Users->jhaip2->Database role membership I set jhaip2 to db_owner (I couldn't log in to the database in the management studio without doing this, probably not the right thing to do?). I then restarted the server.
Now for my java code, it is basically a direct copy of the JDBC Driver 3.0 Sample code except without windows authentication.
package databasetest1;
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB1;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver okay");
con = DriverManager.getConnection(connectionUrl,"jhaip2","jacob");
System.out.println("Connection Made");
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
When I run, it prints out "Driver okay" so I am assuming my driver is set up correctly. Then it prints the error:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'jhaip2'.
It does not matter what username I use, it always fails. I have a feeling I am setting up the user wrong. If anyone could give me some help on how to properly set up a user or any guidance in how to simply connect to a SQL Server database in Java, I would appreciate it.
run this query by selecting your database
CREATE LOGIN aaron792 WITH PASSWORD='12345'
USE BudgetAuthorization
CREATE USER aaron792
i use aaron792 you should use yours
In sql server management studio go to object explorer and right click on (local)(sql server xxx) then go to properties it will open server properties and then go to security and change server authentication mode from windows only to sql server or windows (2nd option)
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2
GO
in server properties , go to permissions and select newly created user from Logins or rules list then below it check all options for grant in explicit rule
open SQL server configuration manager and -> sql server services
at top row SQL server right click and open properties then change built in account to Local System
then restart every thing and make sure it is running. then try your code
I know this has already being answered but would like to give a little twist to it without having to reinstall the whole SQLSERVER RDBMS.
The concept is to change the properties of the sqlserver instance you are trying to connect to.
Step one. Open SQL Management Studio and select the sql server instance from the object explorer.
Right click on the instance and select properties from the popup menu which will open a Server Property Window.
select Security option which is located at the right side of the page. Then change server authentication from Windows Authentication mode to SQL SERVER and Windows Authentication mode (mixed mode).
Select Permissions option afterwards. Then with Permissions selected, select the Login Account you would like to grant permission to. (Login Account should be created before this, check this tutorial out http://www.blackthornesw.com/robo/projects/blackthornepro/HOWTO_-_Creating_a_SQL_Server_Database_Login_Account.htm . The edition might be different from what you have but the concept or workflow remains the same.). Under the permissions, select the Explicit tab, and under Grant, select all the options.
Click OK.
Step Two: to configure the RDBMS to use the internally created Login Accounts. Therefore:
Open/Start SQLSERVER configuration Manager.
Select SQL SERVER Services from the left pane.
With that selected, move to the right pane and right click on SQL Server (MSSQLSERVER) option and then select properties from the popup menu.
SQL Server (MSSQLSERVER) properties window appears, make sure Log On tab is selected, then select the radio button named Built-in Account under Log on as: Option. Then select from the combo box, Local System.
Click OK. By clicking on ok, you will be asked to restart the instance, go ahead to restart it. If restart is not asked, then move to step three below.
Step Three: to restart the SQLSERVER RDBMS.
Go to Control Panel > Administrative Tools > Component Services.
Select Services from the left pane
Then select SQL Server (MSSQLSERVER) from the right pane, the click restart which is just a little to the top right side.
When I looked in the SQL Server log files, it was saying that I couldn't log in because SQL Server was in Windows Authentication mode, even though in the program it was set to Mixed Authentication Mode.
When installing, I had set it up in Windows Authentication mode but changing the settings in the program would not change it from Windows Authentication mode.
I removed SQL Server 2008 and all related programs from my computer and installed a fresh copy, this time with SQL Server Authentication. Everything works correctly now. I don't know why SQL Server had a problem with changing the authentication mode, but it works now so I am happy.
Would this other question possibly be the same issue: MS SQL Server 2005 Express x86 - its port is unreachable - help.
You have to make sure that SQL Server is listening on the correct port before you can connect via a TCP connection using JDBC.
I ran into the same issue. Thank you, jhaip, for pointing me to the right direction: SQL Server was in Windows Authentication mode.
I'd like only to add that it is not necessary to reinstall the SQL server and all related programs. What's just needed is to change authentication mode. See this answer for more details: An attempt to login using SQL authentication failed

Categories

Resources