Connection Issue With Mysql,JDBC on Red Hat Linux - java

I am implementing a class that needs to connect to a MYSQL database....on a windows system, i had some connection issue which were resolved with changing the "bind-address" paramater in the MYSQL configuration file to localhost and setting the MYSQL connector in the classpath.
I tried the same steps on Red Hat Linux,..but no connection is made. Is it something with the security configuration?. Below is the code i am using to test for a MYSQL connection.
import java.sql.*;
public class test {
static Connection con = null;
public static void main(String[]args) throws SQLException,ClassNotFoundException {
//Load Driver
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/IMS","root","root1");
System.out.println("Database Connected");
} catch(Exception e) {
System.err.println("error connecting database: little challenge" + e);
System.exit(2);
}
}
}
The error being returned is
error connecting database:
little challenge java.sql.SQLException:
Unexpected exception encountered during query.
I believe this means the connection is not being made. How can i resolve this?

Looks like a problem related to use of GCJ. It relates to the connection attempt raising an exception when it reaches an unknown character or one it cannot convert.
Recommendation: use Hotspot (a.k.a. Sun) JVM.
Update: To do so, install the JDK rpm and use alternatives command to set the default JVM version as shown on superuser.

Define port of server
jdbc:mysql://localhost:3306/IMS

You have to add mysql jar file in project.After its work also on linux.

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.

Unable to get a SQL-Server connection

Im having difficulties trying to get a connection to my sqlserver database.
The database im using is SQL-Server 2008.
The driver im using is the one i got here: Microsoft download page
I use the following code:
public static final String URL_FORMAT = "jdbc:sqlserver://%s:%s;DatabaseName=%s";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
String connectionURL = String.format(URL_FORMAT, "10.31.3.3", 1433, "EPowerTest");
System.out.println("connecting to: "+connectionURL);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection(connectionURL, "sa", "*************");
if (connection == null) {
System.out.println("no connection was established");
} else {
System.out.println("succesfully connected");
}
}
Now this piece of code runs on my developers machine, im getting the following results:
connecting to: jdbc:sqlserver://...:1433;DatabaseName=******
succesfully connected
But when i run this piece of code on my developers machine it prints the follwing:
connecting to: jdbc:sqlserver://10.31.3.3:1433;DatabaseName=*******
and the second line never gets printed, because it seems DriverManager.getConnection does not return. This is not a firewall issue, since all three terminals (db server, developers machine and the test machine) are all on the same network. Why is my method not returning? am i missing some important SQLServer files?
Hope anyone here can help me with this annoying problem!
Check if the JVM in the machine that the connections hangs is the version 1.6.0_29. If it is, upgrade to a newer Java.
Here is another link explaining the issue.

JDBC Example for java

I have downloaded JDK 6 and also I have sqljdb4.jar and I have database.properties file that content the following data
database.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
database.url=jdbc:sqlserver://.;databaseName=UserInfo;integratedSecurity=true;
database.username=sa
database.password=admin
B.N : I'm installing the server on my machine and the server name = . , also I'm using Windows Authontication
My problem now is when I try to create connection I have the following error
com.microsoft.sqlserver.jdbc.SQLServerException:
The TCP/IP connection to the host
localhost, port 1433 has failed.
Error: Connection refused: connect.
Please verify the connection
properties and check that a SQL Server
instance is running on the host and
accepting TCP/IP connections at the
port, and that no firewall is blocking
TCP connections to the port. at
com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:130)
I don't know what is the exact problem here
If any one can help I will be appreciated
Thanks in Advance
That's caused by many probabilities like
1- IP is worong
2- Port is wrong
3- There is firewall prevent machine to go out and connect to another IP
4- SQL server down .
try to use
public class JdbcSQLServerDriverUrlExample
{
public static void main(String[] args)
{
Connection connection = null;
try
{
// the sql server driver string
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// the sql server url
String url = "jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE";
// get the sql server database connection
connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");
// now do whatever you want to do with the connection
// ...
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
}
}
What i need to explain is there is very good technology called " Persistence " is better than JDBC and is more than brilliant and easy to use .
The problem is that your SQL server is either
not installed,
not running or
not accepting TCP/IP connections.
Particularly the last one is nasty, as I remember that some versions of SQL Server have not configured the TCP/IP connector to run by default.
Well first and foremost we need to see your code. Second looking at the error message the database is A)not running
B) on a different port
or C) the code is incorrect.

How to connect MySQL to Java program

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

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

My configuration:
windows XP SP3
JDBC 2005
MS SQL Server 2008 Express, exposed via tcp/ip on port 1433
sqljdbc.jar in class path
I tried:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
con = DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433/SQLEXPRESS2008;databaseName=Test;selectMethod=cursor", "sa", "");
}
catch (Exception e) {
e.printStackTrace();
}
But it always throws an exception:
java.sql.SQLException: No suitable driver
I also tried the following urls:
localhost:1433/SQLEXPRESS2008
localhost/SQLEXPRESS2008
localhost
Same results.
Any help?
You have the wrong URL.
I don't know what you mean by "JDBC 2005". When I looked on the microsoft site, I found something called the Microsoft SQL Server JDBC Driver 2.0. You're going to want that one - it includes lots of fixes and some perf improvements. [edit: you're probably going to want the latest driver. As of March 2012, the latest JDBC driver from Microsoft is JDBC 4.0]
Check the release notes. For this driver, you want:
URL: jdbc:sqlserver://server:port;DatabaseName=dbname
Class name: com.microsoft.sqlserver.jdbc.SQLServerDriver
It seems you have the class name correct, but the URL wrong.
Microsoft changed the class name and the URL after its initial release of a JDBC driver. The URL you are using goes with the original JDBC driver from Microsoft, the one MS calls the "SQL Server 2000 version". But that driver uses a different classname.
For all subsequent drivers, the URL changed to the form I have here.
This is in the release notes for the JDBC driver.
Download the latest JDBC Driver (i.e. sqljdbc4.0) from Microsoft's web site
Write the program as follows:
import java.sql.*;
class testmssql
{
public static void main(String args[]) throws Exception
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con=DriverManager.getConnection("jdbc:sqlserver://localhost:1433;
databaseName=chapter16","sa","123");//repalce your databse name and user name
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select * from login");//replace your table name
while(rs.next())
{
String s1=rs.getString(1);
String s2=rs.getString(2);
System.out.println("UserID:"+s1+"Password:"+s2);
}
con.close();
}
}
Compile the program and set the jar classpath viz: set classpath=C:\jdbc\sqljdbc4.jar;.; If you have saved your jar file in C:\jdbc after downloading and extracting.
Run the program and make sure your TCP/IP service is enabled. If not enabled, then follow these steps:
Go to Start -> All Programs -> Microsoft SQL Server 2008 -> Configuration tools -> SQL Server Configuration Manager
Expand Sql Server Network Configuration: choose your MS SQL Server Instance viz. MSQSLSERVER and enable TCP/IP.
Restart your MS SQL Server Instance. This can be done also from the right click menu of Microsoft SQL Server Management Studio at the root level of your MS SQL server instance
If your databaseName value is correct, then use this: DriverManger.getconnection("jdbc:sqlserver://ServerIp:1433;user=myuser;password=mypassword;databaseName=databaseName;")
The latest JDBC MSSQL connectivity driver can be found on
JDBC 4.0
The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->
Right Click Project Name --> Properties --> Java Build Path -->
Libraries --> Add External Jars
Also as already been pointed out by #Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname
Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
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");
Statement statement = conn.createStatement();
String queryString = "select * from SampleTable";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
}
}
Hope this helps.
Named instances?
URL: jdbc:sqlserver://[serverName][\instanceName][:portNumber][;property=value]
Note: backward slash
You can try the following. Works fine in my case:
Download the current jTDS JDBC Driver
Put jtds-x.x.x.jar in your classpath.
Copy ntlmauth.dll to windows/system32. Choose the dll based on your hardware x86,x64...
The connection url is: 'jdbc:jtds:sqlserver://localhost:1433/YourDB' , you don't have to provide username and password.
Hope that helps.

Categories