How to create Connection class - java

This is a code i tried for common Connection class jdbc project but it returns only null
package dbDemo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionDemo {
Connection con;
public Connection getConnection() {
try
{
Class.forName("com.mysql.jdbc.driver");
String url="jdbc:mysql://localhost:3306/myserver";
String name="root";
String pwd="admin123";
con=DriverManager.getConnection(url,name,pwd);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return con;
}}
anybody can please help this code right or wrong.

Please change the driver class to
com.mysql.jdbc.Driver
Then you should have the mysql-connector.jar in your classpath.
If it is an eclipse ide just right-click on the project->build path->configure build path->go to libraries that->add external jar->select the mysql-connector.jar from the place you kept after downloading it.

the best way to know the exact error you have to use e.printStackTrace() instead of System.out.println(e.getMessage()) and then execute again it will print all the errors which help you to debug more

Download JDBC jar from here: http://dev.mysql.com/downloads/connector/j/5.0.html and make sure that you include it to Java's CLASSPATH when you run your application.
After you unpack a downloaded zip or tar file, you'll need only one file to make it working: mysql-connector-java-5.0.8/mysql-connector-java-5.0.8-bin.jar
After extracting the JAR file you can run your program like this:
java -cp path-to-mysql-connector-java-5.0.8-bin.jar your-java-class
The suggestion about changing 'driver' to 'Driver' in the driver's class name is also correct.

Related

running Postgresql in Java [duplicate]

I am having some difficulty in making connectivity with Java and PostgreSQL Database.I have download the JDBC4 Postgresql Driver, Version 9.2-1002 driver and properly set the application ClassPath. My code is as under
import java.sql.*;
public class JavaPostGreSQLConnectivity
{
public static void main(String[] args)
{
DB db = new DB();
db.dbConnect("jdbc:postgresql://127.0.0.1:5432/TestDB", "postgres","pwd");
}
}
class DB
{
public DB() {}
public void dbConnect(String db_connect_string, String db_userid, String db_password)
{
try
{
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
System.out.println("connected");
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
Upon running I am getting the below error
Is it complaining about
Class.forName("org.postgresql.Driver");
If so then what will be the driver name? However, I followed this for my learning purpose.
However, If I do
C:\Program Files (x86)\Java\jdk1.7.0\bin>java -cp C:\Users\pos
tgresql-9.2-1002.jdbc4.jar; JavaPostGreSQLConnectivity
connected
It works.Why I need to explicitly mention the driver again when I have already placed it in the classpath properly? Is there any alternative way (I just want to put the JAR file in Classpath and the program should read from there)?
Thanks in advance
The driver name is OK. It is the same as mentioned in the official docs of the driver. Therefore the driver is just not in the classpath.
You say:
I [...] properly set the application ClassPath
On the other hand you start the program by just calling:
java JavaPostGreSQLConnectivity
In that case no PG driver is on the classpath. You have to add it by hand using someting like
java -cp postgresql-jdbc4.jar JavaPostGreSQLConnectivity
EDIT The question has been changed while typing, hence the duplication.
You added the jar only in you IDE. This helps the IDE to compile your code. If you start the program using you IDE then the IDE will also set the classpath for you. But if you don't start via the IDE then nobody knows the correct classpath and it has to be set by hand.
Your options are:
start always via IDE
make some batch script which hides the setting of the classpath (common solution)
set the CLASSPATH environment variable (does not scale with other Java applications)
make an "Executable Jar" and set the classpath there. (Search this site using that term).
put the jar into a place where the JVM picks it up automatically (e.g. in the lib/ext directory of the JRE). But polluting the JRE/JDK libs is the worst option.
Note: This is all basic Java knowledge and has nothing to do with PostgreSQL.

Jar File Error (java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver)

Sir in Netbeans when I run program it runs successfully but when I make jar file and run it then there is this error :
java.lana.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
Please answer me that how to solve that exception.
Here is my code:
public class DatabaseManager {
static Connection con;
static{
System.out.println("Connecting To Database ... ... ...");
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Pepsi");
} catch (ClassNotFoundException | SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
System.exit(0);
Logger.getLogger(DatabaseManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have also used ucanaccess me libariers for direct access to database.
con = DriverManager.getConnection("jdbc:ucanaccess:C:\\Users\\Administrator\\Documents\\NetBeansProjects\\Pepsi\\Pepsi.accdb");
When I ran java while the exception comes but in Netbeans it works properly.
It is running in netbeans IDE because you have all java reference libraries added in your project. Please verify your classpath when running jar directly. I guess your are not having rt.jar in your classpath.
Check this if your are using Java 8 java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?
I guess the some classes are not properly added to your jar file as external dependencies. Please verify that all the external jar files that you are using in your project are successfully added to your jar file.

DriverManager can't open SQL connector jar

It's really weird, but please hear out the story.
We both know the behavior of DriverManager during connector registering. I swear it was worked as expected, then suddenly it started keep throwing SQLException: no suitable driver found. To fix it, I have to break the jar file and expose the content folders directly under the classpath with my bare hand.
I then concluded that something stopped my DriverManager from being able to open the jar file automatically. It looks like a weird access permission problem. My system is windows 8.1 and I run java under administrator:cmd.
import java.sql.*;
public class Test{
public static void main(String... args) throws Exception{
String url = "jdbc:mysql://localhost:3306/bobbooks";
Connection conn = DriverManager.getConnection(url, "root", "password");
}
}
I have few classpath folders, only one of them contains the jar file.
OK, here is the code below, just a simple test class
I really want to fix this problem nicely, without breaking the jar file. Somebody help pls
I wonder if I understood what I was learning, but here I got the solution:
Simply edit the environment variable, to add the jar file as a CLASSPATH, like this:
(CLASSPATH:)
D:\mysql-connector-java-5.1.35-bin.jar;
then it works just fine.

Setting up path Connector/J in windows 7

Can anyone please tell me as to how to setup the path for Connector/j using the "mysql-connector-java-5.1.18-bin.jar" in windows 7?
I'm using the below code and it always end up throwing an exception.
(java.lang.ClassNotFoundException : com.mysql.jdbc.driver)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class LoadDriver
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Connection working");
}
catch (Exception ex)
{
System.out.println("Connection Fail");
System.out.println(ex.getMessage());
}
}
}
I tried following the official documentation of connector/j for setting up the path, but could not understand.
I tried adding E:\PROGRAM FILES\JAVA\jdk1.7.0_01\jre\lib\ext\mysql-connector-java-5.1.18-bin.jar in the "path" environment variable, Please correct me.
First, you dont need newInstance on Class.forName("com.mysql.jdbc.Driver")
Second don't copy jars to your JDK folder, there shouldn't ever bee a need to copy them there. The correct thing to do is add the jar to your project as a dependency. If your not using an IDE, then you want to add the jar to java.exe as a --classpath option when you run your code (run "java.exe /?" for more details). If you're using eclipse, you should add the mysql jar to the project by clicking on the project and selecting "properties" and then "Java Build Path" there will be an "Add JARs..." button on the right. Then the IDE will add it to your classpath automatically.

I'm having trouble embedding HSQLDB into a simple Java (Eclipse) project

After reading up on some options (sqlite, derby etc...), I've decided to throw down with HSQLDB. I've downloaded it, read up on it and followed a 'hello world' type intro to it, and am now stuck.
I believe that you have to put the hsqldb.jar file in the src folder, so I did exactly that. Then I made a reference to the package with Eclipse by going into Run -> Run Configurations, then going into the Classpath tab, then clicking User Entries, then add External Jar, and selecting hsqldb.jar.
I get this :
java.lang.ClassNotFoundException: org.hsqldb.jdbcDriver
Here's my code :
package mysqlite;
import java.sql.*;
public class myclass {
public static void main(String[] args) {
try {
Class.forName("org.hsqldb.jdbcDriver");
String url = "jdbc:hsqldb:db";
String user = "aUser";
String password = "";
Connection conn = DriverManager.getConnection(url, user, password);
}
catch(Exception e) {
System.out.println(e.toString());
}
}
}
I understand it's unable to find a class, but I thought that was what the hsqldb.jar provided.
No, you do not have to put it into src folder. src is for source files (*.java). You have to add this jar into your classpath: click on project properties, choose "Java build path", select tab "Libraries" and add the jar here.
The jar can be stored anywhere in your file system. Sometimes people create lib directory under project home and put all 3rd party dependencies there.
Try putting the .jar here:
<YOUR_JAVA_HOME>\jre\lib\ext

Categories

Resources