How to connect MySQL to Java program - java

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");

Related

sybase java DB connection issue

I want to create sybase DB connection in java application.
I've added jconn4.jar to my project, but when I'm connecting to DB in code I have exception ClassNotFoundException: com.sybase.jdbc4.jdbc.SybDriver.
My connection:
SqlConnect() {
try {
DriverManager.registerDriver(new com.sybase.jdbc4.jdbc.SybDriver());
} catch (SQLException e) {
System.err.println("SQL exception " + e.getMessage());
}
}
And also
public void connect() {
try {
connection = DriverManager.getConnection("jdbc:sybase:Tds:localhost:5000", "DBA", "sql");
connection.setAutoCommit(false);
} catch (SQLException e) {
}
}
I want to connect to demo PowerBuilder database, with params:
DSN=EAS Demo DB V125;UID=dba;PWD=sql
What I'm doing wrong?
ADDED
Also when I'm trying to create database connection via intelij database work plugin i also have the same error.
Make sure you have respected jars included on your classpath.
The following works for me:
Use Class.forname to load the drivers
Recommended Approach:
Class.forName("sybase.jdbc.sqlanywhere.IDriver")
con = DriverManager.getConnection("jdbc:sqlanywhere:uid=DBA;pwd=sql");
Another way around:
DriverManager.registerDriver((Driver) Class.forName("sybase.jdbc.sqlanywhere.IDriver").newInstance());
con = DriverManager.getConnection("jdbc:sqlanywhere:uid=DBA;pwd=sql");
The following link will help you in installing drivers:
How to connect Sybase database using Java code in NetBeans?
So, the other jdbc type driver resoled my problem - I connected sajdbcX driver and changed connection string:
connection = DriverManager.getConnection("jdbc:sqlanywhere:uid=DBA;pwd=sql");
So, also thanx Mark Rotteveel for advice - I removed driver register code as redurdrant.
And thank all for ideas.

JDBC connect to host but not in database

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

Difficulty connecting to database using SQLserver jdbc

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");

Connect to Oracle DB with Java

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

Connect to DB (Derby)

I try to connect to the database with this code:
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
String url = "jdbc:derby://localhost:1527/sample";
Connection con = DriverManager.getConnection(url);
PreparedStatement pstmt=con.prepareStatement("insert into app.discount_code values('A',22)");
pstmt.executeUpdate();
con.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
..but not result. What do I need to do to connect to the DB?
Sir, You are connecting to derby network server. So you need to firstly config the environment and start the network server. Please also check the jdbc driver jars are correct.
About how to config and start derby network server.Look at here.
http://db.apache.org/derby/papers/DerbyTut/ns_intro.html#ns_config_env
Also you'd better put the close method in your finally block.
You'd better paste your error message, it wil be helpful to find your problem.

Categories