Connectivity error Java MySQL - java

I've installed MySQL Connector J, WAMP [which comes with MySQL], and Java JDK 1.7 but it always through exception com.mysql.jdbc.Driver
The code
import java.sql.*;
public class sou
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost/cms";
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
conn.close();
}
catch (Exception e)
{
System.err.println (e.getMessage());
}
}
}
I'm compiling this as
C:\Users\Sou\Desktop>javac -cp "D:\Program Files\MySQL\Connector J 5.1.20.0\mysql-connector-java-5.1.20-bin.jar" sou.java

You have to include mysql-connector-java-5.1.20-bin.jar in your CLASSPATH while compiling and running an application.
C:\Users\Sou\Desktop>javac -cp .;"D:\Program Files\MySQL\Connector J 5.1.20.0\
mysql-connector-java-5.1.20-bin.jar" sou.java
C:\Users\Sou\Desktop>java -cp .;"D:\Program Files\MySQL\Connector J 5.1.20.0\
mysql-connector-java-5.1.20-bin.jar" sou
And no need to call the newInstance() method.
Connection conn = null;
try{
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost/cms";
Class.forName ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url, userName, password);
}
catch (Exception e){
System.err.println (e.getMessage());
}finally{
if(conn!=null){
try{
conn.close();
}catch(Exception ex) { }
}
}

You can try this :
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
instead of
Class.forName ("com.mysql.jdbc.Driver").newInstance ();

Insert this code in your program to check for classpath
System.out.println(System.getProperty("java.class.path"));

Related

Unable to connect MS SQL server via Java Class

I am getting error when I try to connect database
Error:com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to
Ptakip.Connection
Ptakip is my Package
Connection is my Class
Here is the Connection Class Code ;
import java.sql.*;
public class Connection {
private Connection cn;
public Connection connector( )
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:sqlserver://localhost\\MyServer:
1433;databaseName=TEST;user=Glassfish;password=pass;");
System.out.println("connected");
}
catch(Exception ex) {
System.out.println("Error:" + ex.getMessage());
System.out.println(cn);
}
return cn;
}
}
your class has the same name as the class in the package java.sql that's why u have this conflict ,juste try to change the name to Connexion ,it should work
Try to make a connection like this. it may help you
String url = "jdbc:mysql://localhost:3306/";
String dbName = "demo”
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "mypasswd";
try {
Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url+dbName,userName,password);
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}

How to connect JDBC to tns oracle

I can connect from plsql to database using tns file
Now I want to connect to the database from my Java using JDBC.
What I tried:
I search google and I find that I have to using this connection String:
"jdbc:oracle:thin:#//host:port))/tnsfile)";
My computer name is myPC
The port that is written in the tnsfile is 5151
So I tried this connection String
"jdbc:oracle:thin:#//myPC:5151))/tnsfile"
but I got this Exception
java.sql.SQLRecoverableException: IO ERROR: SO Exception was generated
What am I doing wrong?
How to connect my JDBC to the database using tns file?
You have to set a property named oracle.net.tns_admin to point to the location of the folder containing your tnsnames.ora file. Then you specify the entry from that file after the # sign in your DB URL. Check example below. You can find more information here: Data sources and URLs - Oracle Documentation
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
System.setProperty("oracle.net.tns_admin", "C:/app/product/11.2.0/client_1/NETWORK/ADMIN");
String dbURL = "jdbc:oracle:thin:#ENTRY_FROM_TNSNAMES";
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = null;
Statement stmt = null;
try {
conn = DriverManager.getConnection(dbURL, "your_user_name", "your_password");
System.out.println("Connection established");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT dummy FROM dual");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (stmt != null) try { stmt.close(); } catch (Exception e) {}
if (conn != null) try { conn.close(); } catch (Exception e) {}
}
}
}
Example entry from tnsnames.ora file:
my_net_service_name=
(DESCRIPTION=
(ADDRESS=(some address here))
(CONNECT_DATA=
(SID=some_SID_name)))
Where my_net_service_name string is what you have to subsitite for ENTRY_FROM_TNSNAMES from my Java example.
Rather than hard code the path to tnsnames.ora, better to find it from the environment:
public static void setTnsAdmin() {
String tnsAdmin = System.getenv("TNS_ADMIN");
if (tnsAdmin == null) {
String oracleHome = System.getenv("ORACLE_HOME");
if (oracleHome == null) {
return; //failed to find any useful env variables
}
tnsAdmin = oracleHome + File.separatorChar + "network" + File.separatorChar + "admin";
}
System.setProperty("oracle.net.tns_admin", tnsAdmin);
}
Try the following:
System.setProperty("oracle.net.tns_admin", PATH_TO_TNSNAMES.ORA);
Class.forName ("oracle.jdbc.OracleDriver");
dbUrl = "jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST="+IPHOST+")(PORT="+PORT+"))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME="+DBNAME+")))"
conn = DriverManager.getConnection(dbUrl, USERNAME, PASSWORD);
Be sure to have the latest version of ojdbc.jar

No suitable driver found for jdbc:mysql//localhost:3306/test

I am trying to write a java program connecting to a MySQL database. But I am getting this error:
No suitable driver found for jdbc:mysql//localhost:3306/test
I have already installed mysql-connector-java.5.1.23-bin.jar. I am still getting this error.
Here is my program:
package database_practice;
import java.sql.*;
public class CreateConnection {
private Connection conn = null;
public static void main(String args[]) {
CreateConnection conn = new CreateConnection();
conn.getConnection();
}
public Connection getConnection() {
try {
String url = "jdbc:mysql//localhost:3306/test";
String username = "root";
String password = "admin1234";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, username, password);
System.out.println("Database Created...!!!");
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Error occured while connecting to database");
}
return conn;
}
}
Your connection string is wrong. This:
"jdbc:mysql//localhost:3306/test"
should be:
"jdbc:mysql://localhost:3306/test"
Note the colon after "mysql".

how to access connection object in another class in java?

i am using xampp mysql, this code is for JDBC program. actually there are two class one is dbconnect.java and another is login.java. I want to access the connection object (i.e. conn) in another class(i.e. login.java). But i don't have proper idea, i have included the code here please suggest me what is the problem and what are the solutions?
This is the code of dbconnect.java
package stundentrecord;
import java.sql.Connection;
import java.sql.DriverManager;
public class dbconnect {
public void conect(){
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "studentRecord";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
if(con==null){
System.out.println("Connection cannot be established");
}
// con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
and here is the code from another class named login.java
if(source==login){
if(username!=null && password!=null) {
Connection conn= null;
Statement stmt = null;
dbconnect db = new dbconnect();
db.conect();
String query = "SELECT * from userlogin";
try{
stmt=(Statement) conn.createStatement(); // here is the problem
ResultSet rs = stmt.executeQuery(query); // here is the problem
while (rs.next()) {
String user = rs.getString("username");
String pass=rs.getString("password");
System.out.println("Welcome "+user);
}
} catch(SQLException ex){
ex.getMessage();
}
StundentRecord SR = new StundentRecord();
} else {
JOptionPane.showMessageDialog(null,"Username or password field is empty","error !!",JOptionPane.ERROR_MESSAGE);
}
}
What is the real problem and how to solve it?
The easiest way would be to make the connect method non void and return the connection:
public Connection conect() {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "studentRecord";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
if (con == null) {
System.out.println("Connection cannot be established");
}
return con;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
You should return your CONNECTION object from you connection class and assign it to your login class... Now your connection object is null...

How to make a MySQL Connection in JAVA

I can't seem to get a connection made on my Java program to java, I have started the MySQL Server, made a database in phpMyAdmin. But I'm confused on how I should use the JDBC Driver that I downloaded from MySQL.
Here's my code:
private void startConnection()
{
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "bank";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
System.out.println("NO CONNECTION =(");
}
}
I had included the jar file in my JDK - jre\lib\ext folder but nothing. Any ideas?
Thanks in advance.
One thing stands out: you haven't specified a network port in the URL. The default port is 3306. So try:
jdbc:mysql://localhost:3306/
For the URL.
You have to specify the port. It's String url = "jdbc:mysql://localhost:3306/"; by default.
private void startConnection()
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "bank";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}
catch (Exception e)
{
System.out.println("NO CONNECTION =(");
}
}
This will work

Categories