This is my first Java application and I'm completely inexperienced with Java and NetBeans.
I have been trying to connect to sql and get some records for 2 days. The problem is about jdbc driver, let me explain. I have downloaded sqljdbc driver and then followed these steps:
Right-click Project->Select Properties->On the left-hand side click Libraries->Under Compile tab - click Add Jar/Folder button and select sqljdbc4.jar file. Then it should be ok, right?
Then I wrote this code But I cant get rid of this exception:
Exception in thread "main" java.lang.ClassNotFoundException:
com.microsoft.sqlserver.jdbc.SqlServerDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at javaapplication1.JavaApplication1.main(JavaApplication1.java:30)
This is the code
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:sqlserver://.\\SQLEXPRESS;databaseName=Northwind; Integrated Security = SSPI ";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SqlServerDriver");
con = DriverManager.getConnection(url);
String sql = "Select Top 3 from * person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
According to this page, the class is called SQLServerDriver and not SqlServerDriver. Case is important!
So, try:
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Note that with newer versions of JDBC, it's not necessary to load the driver class explicitly with Class.forName(...). The page I linked to explicitly explains that you don't have to do it. So, you can just remove the whole line and then it should work.
Java: JDBC Connectivity with MSSQL in NetBeans
Steps
Download JDBC from:
https://www.microsoft.com/en-in/download/details.aspx?id=11774
Run sqljdbc__enu.exe - unpack this zip file in %Program
Files (x86)% with the default directory: Microsoft JDBC DRIVER
for SQL Server
Create your new project in NetBeans
Right Click on the project - select Properties - select Libraries
from left panel - click Add JAR/Folder button - select your JAR file
and open - ok
Open Sql Server Configuration Manager - select Protocols for
SQLEXPRESS under Sql Server Network Configuration - Right Click on
TCP/IP - select Properties - change Enable to Yes - Click IP
Addresses - Goto IPAll - Change TCP Dynamic Ports to 49169 and TCP
Port to 1433 - Apply - Ok - Restart the Computer
Open Run and type Services.msc - Start SQL Server Browser
Goto project and write code for database connectivity.
Code for Local Database Connectivity:
String url = "jdbc:sqlserver://YOUR PC NAME;instanceName=SQLEXPRESS;DatabaseName=dbname;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection myCon = DriverManager.getConnection(url);
Statement myStmt = myCon.createStatement();
ResultSet myRs = myStmt.executeQuery("select * from table name");
I have an update about this issue.
Go to this link, find your compatible JDBC driver (I dowloaded 6.0 version).
Find the appropriate jar in the file you downloaded (I used jre7\sqljdbc41.jar).
For Intellij Idea press Ctrl+Shift+Alt+S and open Project Structure then in the dependencies section add your jar file.
I hope it works for you too.
Related
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 2 years ago.
When I run my code, I get this error: Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.Driver; with a stack trace link to line 13 (Highlighted in the code)
I have just started using JDBC and don't know much about it, but I'll go through what I have done so far to get to where I am. As a preliminary, I am using MySQL Workbench and Apache Netbeans 11:
1) Downloaded the .jar connector file
2) Could not find the build path on netbeans 11 and did some research and couldn't find any resources linking to it, so instead used the Driver dropdown through the databases section on the services tab. Now I can see all my SQL databases and tables in my netbeans IDE.
3) Wrote the following code using the 7 steps to connect to the database, establish a connection etc
import java.sql.*;
public class GroundControlToMajorTom {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306//customers";
String uname = "root";
String pass = "";
String query = "SELECT customer_id FROM customers WHERE customer_id = 1";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
rs.next();
String id = rs.getString("customer_id");
System.out.println(id);
st.close();
con.close();
}
}
4) Run the code and get a ClassNotFoundException. I did a bit of research and it seems to say that I don't have the connection to the actual driver, but I added it in the drivers section of the services for my project?
Any help would be much appreciated my dudes <3
Add com.mysql.jdbc.Driver to CLASSPATH.
If you use maven, add to <dependencies> section of pom.xml the dependency of required driver (mysql-connector-java):
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
for gradle
compile group: 'mysql', name: 'mysql-connector-java', version: mysqlVersion
You need to add the downloaded JAR to the classpath.
Try this instruction:
Open NetBeans and right-click on the project name in the Projects tab.
Select Properties.
Select Libraries.
Click the Add Jar/Folder button.
Navigate to the directory where the downloaded JAR files are.
Iam new on using NetBeans 7.4 , i want to connect my java application to MYSQL , the application is desktop application .
i have already install MYSQL workbench 5.2 and create database with one table .
from NetBeans services on Databases i register MYSQL server , i enter these values :
localhost : 127.0.0.1 , user : root and password : root.
NetBeans ask me to set MYSQL command Path (Path to start command) i insert this path :
C:\Program Files\MySQL\Connector ODBC 5.1\myodbc-installer.exe
from main class in java i saw from net how to set connection :
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/sameer", "root","root");
System.out.println("Connected database successfully...");
} catch (Exception e) {
System.out.println(e);
}
but all time the exception will execute :
java.sql.SQLException: No suitable driver found for jdbc:mysql://127.0.0.1:3306/sameer
You need to include the mysql connector jar in your project.
If you haven't downloaded it yet you can find it here http://dev.mysql.com/downloads/connector/j/
Once you have downloaded it:
right click on the project
select Properties
select Libraries -> Add JAR/Folder
navigate your file system to select the jar you previously downloaded
save and it will run correctly
I want connect my MS access file with Java GUI program,but I have problem with connection....
I have Windows 7 64b, and ms office 2007.
When I opened the ODBC driver manager in the control panel I havent found any driver for Microsoft Access (maybe when I started the ODBC is started running the 64bit ODBC, now I think is running the 32bit ODBC.
I read this and I make it :
"jdbc-odbc connection for window 7 64 bit machine..
1 . Right click Data source (ODBC)..go to properties change the folloing thing
target [ %SystemRoot%\SysWOW64\odbcad32.exe ]
start in : [ %SystemRoot%\System32 ]
press enter and continue as admin source: source link
"
) Now when I start in conctrol pannel the ODBC I can see the driver screenshoot
My program code(I tried two ways but I have same error):
public void Connect() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// String DatabaseFile = "D:java/Invertory.mdb";
// String DATABASE =
// "jdbc:odbc:Driver="
// + "{Microsoft Access Driver (*.mdb, *.accdb)};"
// + "DBQ=" + DatabaseFile;`enter code here`
String DATABASE ="jdbc:odbc:Driver= Microsoft Access Driver (*.mdb, *.accdb);DBQ=Invertory.mdb";
CONEX = DriverManager.getConnection(DATABASE);
} catch (Exception X) {
X.printStackTrace();
//JOptionPane.showMessageDialog(null,e);
}
}
error
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
Use UCanAccess JDBC Driver :
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<mdb or accdb file path>",user, password);
for example:
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://c:/pippo.mdb");
So for your example it will be Connection conn=DriverManager.getConnection("jdbc:ucanaccess://"+path)
If you are using Windows 64-bit you probably need to go to this path
C:/Windows/SysWOW64/odbcad32.exe
Then I noticed that you are using the direct path instead creating new System DSN, your direct path is correct till the path to the access file you must give the full path like this :
jdbc:odbc:Driver= Microsoft Access Driver (*.mdb, *.accdb);DBQ=path/to/Invertory.mdb"
To get the path you probably need to use java.io.File that have a method returns the abslute path to the file see the example :
import java.sql.*;
public class TestConnection {
Connection con ;
Statement st ;
ResultSet rs ;
String db;
public TestConnection (){
try{
String path = new java.io.File("Invertory.mdb").getAbsolutePath();
db ="JDBC:ODBC:Driver=Microsoft Access Driver (*.mdb, *.accdb); DBQ="+path;
doConnection();
} catch(NullPointerException ex){
ex.printStackTrace();
}
}
public void doConnection(){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(db);
st = con.createStatement();
rs = st.executeQuery("select * from Invertory");
while(rs.next()){
System.out.println(rs.getObject(1));
}
}catch(SQLException | ClassNotFoundException ex){
System.out.println(ex.toString());
}
}
public static void main(String...argS){
new TestConnection();
}
}
I answered a similar question enter link description here a while back.
Basically at that time:
You could connect to Ms-Access from 32 bit java through the JDBC-ODBC bridge
You could not connect to a 32 bit Odbc driver through the JDBC-ODBC from 64 bit java. There was a message telling you that you can only connect from a 32 bit programs
While Microsoft does provide a 64 bit Ms-Access driver, it did not work with Java's 64 bit JDBC-ODBC driver.
Since then there seems to be a new open-source Ms-Access JDBC Driver Ms-Access JDBC driver. I have no Idea how good it is.
You just missing something in your code right here :
db ="JDBC:ODBC:Driver=Microsoft Access Driver (*.mdb, *.accdb); DBQ="+path;
You need to add {} between Driver= and )=; .
Like this Below
db ="JDBC:ODBC:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ="+path;
final String fileName = "c:/myDataBase.mdb"
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="+fileName;
Connection con = DriverManager.getConnection(url,username,password);
The problem is that you should run on Java 32 bit try to install latest JDK and it will work
I run it using JDK version "jdk-7u67-windows-i586.exe"
On a 64 bit system, you should:
run as admin accessdatabaseengine_64.exe
run java - 7-64 bit - jre.
if you are working in NETBEANS then after unzipping ucanacess.zip file add all jar file in the classpath using property window of project click on compile tab and add jar file then compile and test app.
JDBC-ODBC MS-ACCESS CONNECTION STOPPED WORKING IN JDK8. I solved the issue by installing JDK7 along with JDK8 in the same PC, once installed JDK7 I assigned it as the JDK version to use in my project as follows in Netbeans:
1.RIGHT CLICK THE PROJECT IN THE LIST > CLICK PROPERTIES
2.CLICK LIBRARIES ON THE LEFT NAVIGATION TREE
3.CLICK BUTTON MANAGE PLATFORMS > CLICK BUTTON ADD PLATFORM...
4.FOLLOW WIZARD, DESPITE IT SHOWS JAVA STANDARD EDITION CLICK NEXT
5.NAVIGATE TO C:\Program Files (x86)\Java AND SELECT THE FOLDER OF JDK7 > CLICK NEXT
6.THE FIELD AUTOFILL WITH THE RIGHT INFO... > THEN CLICK FINISH
7.SELECT THE JDK PLATFORM FROM THE LIST > CLICK CLOSE > OK
8.JDK7 SHOULD SHOW IN LIBRARIES PACKAGE.
JDK7 in Libraries Package
Click Back in Browser to return here after looking at the image...
From here on everything must run smoothly.
Hope it solves your problem.
Thanks.
I am attempting to connect to a mysql database, with a connection url of:
jdbc:mysql://127.0.0.1:3306/test
I have downloaded the coorect Mysql driver to connect with the database, and have tried a multitude of approaches to set the driver, with each not working. So far I have tried placing the JAR file in the following places (and changing the PATH environment variable accordingly)
JRE/LIB/
JDK/LIB/
JRE/LIB/mysql-connector-java-5.1.21
JDK/LIB/mysql-connector-java-5.1.21
The path for the JAR file has been its location + mysql-connector-java-5.1.21-bin.jar
Over the last 4+ hours I have read multiple questions and solutions on StackOverflow, as well as online tutorials about this issue, and none have solved the problem.
I have been using the following code to attempt a connection
import java.sql.*;
import java.util.Date;
public class DatabaseHelper{
private Connection conn = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
private String url = null;
public DatabaseHelper(){
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test");
System.out.println("Driver Loaded!");
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
Stacktrace
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at DatabaseHelper.<init>(DatabaseHelper.java:28)
at DatabaseTest.<init>(DatabaseTest.java:6)
at DatabaseTest.main(DatabaseTest.java:14)
You need to add the JAR to your classpath. When launching the java app, simply put:
java -cp mysql-connector-java-5.1.21-bin.jar TheNameOfYourMainClass
i faced this problem before while working on a project, I put the jar file in 2 locations, what worked for me was as follows:
I put the mysql jar in JAVA_HOME/JRE_FOLDER/lib/ext/
then the other thing is that i create a libs folder inside the project (directly in the project's folder) and also put the mysql jar inside it. After that add the jar (the one inside the libs folder) to the building path of the project.
If you use Eclipse, adding the jar to the building path is done by right-clicking on the jar and choosing "Build Path" from the menu and then choosing "Add to Build Path".
Hope this helps,
Before I begin I would like to mention that I have researched this thoroughly and have yet to find a solution which has worked for me (a good 2-3 days of research).
Currently using :
WAMPServer Version 2.1 (Apache service disabled)
Eclipse-jee x64
javac 1.6.0_22
Windows 7 x64
The applet, webpage, and database are all residing on my local computer.
First and foremost my applet works without issues in the Eclipse IDE, however I am constantly recieving the following error when attempting to run it as applet.html with the following script:
<applet code="GUI.class"
name="Some name goes here"
archive="APTracker.jar"
width="1000" height="700">
Your browser is not Java enabled.
</applet>
I have exported my class files using Eclipse IDE which has included the manifest into appletJar.jar.
The Jar exported by Eclipse does NOT contain the mysql-connector library
After assembling my class files I manually extracted the com and org files from the mysql-connector jar and
input them into my appletJar.jar
Following this I signed my applet jar (and confirmed it is signed) with a key which expires in 6 months.
After these steps I still receive the error message shown below.
I have tried replacing localhost with 127.0.0.1 which did not work. I have also tried placing the mysql-connector.jar
in the jre, jdk, and root class files which showed no change.
private final String DRIVER = "com.mysql.jdbc.Driver";
private final String DATABASE_URL = "jdbc:mysql://localhost:3306/javadb";
private final String USERNAME = "xxxxxx";
private final String PASSWORD = "xxxxxx";
private Connection connection = null;
private PreparedStatement selectAllAirports = null;
private ResultSet resultSet;
private ResultSetMetaData metaData;
/* Establish PreparedStatements */
public ResultSetTableModel()
{
try
{
//establish connection to database
connection = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
//load driver class
Class.forName( DRIVER );
//create prepared statements
selectAllAirports = connection.prepareStatement( "SELECT asciiname, latitude, longitude, elevation, timezone, country_code FROM geoname;" );
}
catch ( SQLException sqlException )
{
sqlException.printStackTrace();
//System.exit(1);
}
catch ( ClassNotFoundException classNotFound )
{
System.out.println("ClassNotFoundException triggered.");
classNotFound.printStackTrace();
}
}
This is the error message which I receive:
C:\Users\Mr.\Desktop\Applet>appletviewer applet.html
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/javadb
at java.sql.DriverManager.getConnection(DriverManager.java:602)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at ResultSetTableModel.(ResultSetTableModel.java:38)
at GUI.(GUI.java:20)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:785)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:714)
at sun.applet.AppletPanel.run(AppletPanel.java:368)
at java.lang.Thread.run(Thread.java:662)
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
at GUI.init(GUI.java:60)
at sun.applet.AppletPanel.run(AppletPanel.java:424)
at java.lang.Thread.run(Thread.java:662)
Note that recent JDBC drivers don't need the Class.forName() call if the service loader method is supported.
The current Connector/J version does support that, but by including only the org and com directories of the JDBC driver you "broke" it: The service loader mechanism depends on files under the META-INF directory.
So with your setup you would indeed need the Class.forName() call. But in your code that code is after the attempt to get the connection, which won't do any good.
So do one of those:
Add the relevant service files from the JDBC driver (under META-INF/services) to your jar file (and get rid of the unnecessary Class.forName() call) or
Put the Class.forName() call before the DriverManager.getConnection() call.
Rather than trying to manually put the MySQL class files into your APTracker.jar, why not just include the MySQL jar on the applet's classpath?
I suspect there is something in the MySQL jar file's META-INF directory that you need - a ServiceLoader configuration file or some such.
Things to consider are:
Do you have mysql-connector-java-5.1.10.jar or any related connector in your machine? If none, ask it in google?
If you have, paste the connector at C:\Program Files\Java\jdk...\jre\lib\ext directory.
Edit the applet tag on archive as archive = APTracker.jar, mysql-connector-java-5.1.10.jar
Paste again the mysql-connector-java-5.1.10.jar to where the files like .html, .class and the like are located.
I guess the MySQL JDBC jar is missing.
you can download that jar from: http://www.mysql.com/downloads/connector/j/