Make a connection to a MS SQL database in the local machine - java

I am trying to access a database which is located in my C drive in my local machine. I can access the data base through Microsoft SQL server Management Studio. However as the data base is not in a server my first question is "if even it's possible to access it through my java code."
-I have tried my local machine address and also the name of the server however non of them seems to be working.
String url = "jdbc:sqlserver://DAVE-PC\\SQLEXP/";
String dbName = "STORESQL";
// String driver = "com.mysql.jdbc.Driver";
String userName = "dave-PC\\dave";
String password="";
try {
// Class.forName(driver).newInstance();
Connection con =DriverManager.getConnection(url+dbName,userName,password);
java.sql.Statement stm= con.createStatement();
*DAVE-PC\SQLEXP/" is the name of my database. The username and password are windows authentication.
My second question is if I can't access the database like this, Is there any virtual server (compatible with microsoft SQL) that I can copy the database there and access it from the?

I think your mistake is in userName. for your PC you can try LOCALHOST or 127.0.0.1 Perhaps you would try this method to connect:
try{
server = "jdbc:sqlserver://127.0.0.1:1433;databaseName=STORESQL;selectMethod=cursor";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(server,"dave",password);
}catch(SQLException e){
System.out.println(e);
}catch(ClassNotFoundException e){
System.out.println(e);
}

Related

SQLException while connecting to Azure SQL Data Warehouse using JDBC

I am trying to connect to Azure SQL Data Warehouse through JDBC. I am getting the following exception.
*
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host tcsqldatawh.database.windows.net, port 1433 has failed. Error: "null. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:191)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:242)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2280)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:493)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1387)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1068)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:904)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:451)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1014)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at testsqldw.SQLDatabaseConnection.main(SQLDatabaseConnection.java:30)
*
I have seen similar questions asked about connecting to the SQLServer DB here.
I configured the database to allow access to my IP using the process here.
Please check the code below:
package testsqldw;
import java.sql.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://databaseserver.database.windows.net:1433;"
+"database=databaseserver;"
+"user=username#databaseserver;"
+ "password=password;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
System.out.println("Total connection string is---\n"+connectionString);
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String createSql = "create table employee(employee_id varchar(20));";
statement = connection.createStatement();
boolean status=statement.execute(createSql);
System.out.println(status);
// Print results from select statement
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the connections after the data has been handled.
if (statement != null) try { statement.close(); } catch(Exception e) {}
if (connection != null) try { connection.close(); } catch(Exception e) {}
}
}
}
Total connection string is
jdbc:sqlserver://databaseserver.database.windows.net:1433;database=databaseserver;user=username#databaseserver;password=password;encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
Please help me in resolving the issue.
Per my experience, the issue may be caused by the following reasons:
The SQL Server which you have created may not work fine.
You may use incorrect JDBC connection string.
For the first reason, you could use some client tools to connect to the SQL server. If you could connect to the server, that indicates the SQL server is ok.
If not ,you could create a new SQL Server. After then, you could create a new SQL Data Warehouse according to this URL https://azure.microsoft.com/en-us/documentation/articles/sql-data-warehouse-get-started-provision/.
The URL also includes the firewall config method.
I use the SQL Server InTouch to connect to the SQL Server. The followings are some description images.
You could get the parameters by the Azure Portal. The port number is 1433.
The following picture indicates that your server is ok.
For the second reason, you could copy the connection string from the azure portal and modify the password only.
Hope it helps. Any concerns, please feel free to let me know.

What will i write inside my Class.forName if i have jdbc:mysql://localhost:3306

im just really new to java and i have a hard time just to connect the database.
thank you for the help
i tried the derby but my database is in mysql using xampp.
Statement stmnt;
ResultSet rs;
try{
String host = "jdbc:derby://localhost:3306/population";
String uName= "root";
String uPass="root";
Connection con = DriverManager.getConnection(host, uName, uPass);
//execute some sql and load into the result set
stmnt = con.createStatement();
String sql = "SELECT * FROM users_admin";
rs = stmnt.executeQuery(sql);
//move the cursor the first record and get the data
rs.next();
int id = rs.getInt("admin_id");
String id_admin = Integer.toString(id);
String username=rs.getString("username");
String pwd = rs.getString("password");
ta_user.setText(username);
ta_pwd.setText(pwd);
ta_id.setText(id_admin);
}
catch( SQLException err ){
System.out.println( err.getMessage());
}
I've tried that, code in my other sample project and it shows an error:
java.net.ConnectException : Error connecting to server localhost on port 3306 with message Connection refused: connect.
Good news! You don't need a Class.forName and your JDBC driver loaded successfully. Now you need a mysql sever, or derby server you use two different jdbc url(s) in the question, listening on port 3306 to connect to.
You don't need it. Connection refused indicates that your driver is working perfectly, and that your MySQL or Derby database server (whichever of the contradictory URLs in your title and question is to be believed) isn't started, or possibly even installed, on the localhost.

How to connect to a database using a distributed API?

I'm having trouble with my distributed application in java netbeans the program is running perfectly on the original machine where i created it. but when i build it and make a distribute folder and follow the instructions and try to run it, I got an error that localhost on port 1527 has been refused.
here is my code on my do connect function
public void DoConnect()
{
String host = "jdbc:derby://localhost:1527/KempDB";
String uName = "main";
String uPass = "admin";
try
{
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select cv.checkvouchernumber, c.checknumber, paytoorder, bankcode, dateissued, amount from checkvoucher cv, checks c where cv.checkvouchernumber = c.checkvouchernumber and cv.checknumber = c.checknumber";
rs = stmt.executeQuery(sql);.....
..........
}
catch(SQLException err){
.......
}
so this is the code I used to connect with the database server, the database server I used is built-in with java. Its a apache derby...
like I said in the original machine where I created the program runs ok without errors but when I distribute the program to another machine there's an error refusing the connection.
How can I connect to the local machine where my database is? maybe you can help me on this.
Are the database Servers running on these machines?
Are u starting the database server programmatically?
If you try to connect a database Server with:
jdbc:derby://localhost:1527/KempDB
This Server needs to be up and running.
For your case you should use an embedded Database.
For the case your Database is already an embedded Database, then you can try using this URL:
jdbc:derby:KempDB
instead of:
jdbc:derby://localhost:1527/KempDB
Hav a look on this one

Connect to mysql remote database using JDBC?

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/

error connecting to mysql using java

i ran into a weird problem when connecting to mysql using java.
i'm running xampp with tomcat
i tried connecting to mysql from java. on my machine it works fine, but on a friends machine i get an error: access denied for user 'tomcat'#'localhost'
thing is - i managed to connect with the exact same info using php.
the java code for the connection is:
String url = "jdbc:mysql://localhost:3306/";
String dbName = "mta_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "tomcat";
String password = "tomcat";
try {
Class.forName(driver).newInstance();
_conn = DriverManager.getConnection(url + dbName, userName, password);
} catch (Exception e) {
e.printStackTrace();
}
port is fine
any idea what could be the cause?
The error is probably on the MySQL side, that is, the tomcat user doesnt have privileges to connect from non-localhost.
For simplicities sake you can first create an account that is able to connect from anywhere, via the MySQL GRANT statement like so:
GRANT ALL ON mta_db.* to tomcat#'%' identified by 'yourpassword';
In this case the % is a wildcard for any host.
If you know the actual IPs of your connecting clients you can later crack it down, to be more security conscious.

Categories