Skip to main content

connecting to MySQL with java

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
Alpal
Offline
Joined: 2011-07-07

So ive been working with java for awhile but im just now cracking the shell into working with Databases with my Apps,

ive installed MYSQL and can work with it useing statement command dirrectly with mySQL however i would like to connect to my sever in java so i picked up this snipet of code :

Connection conn = null;

1 try
2 {
3 String userName = "root";
4 String password = "admin";
5 String url = "jdbc:mysql://localhost:3306/test";
6 // com.mysql.jdbc.Driver
7 Class.forName("com.mysql.jdbc.Driver").newInstance();
8 conn = DriverManager.getConnection (url, userName, password);
9 System.out.println ("Database connection established");
10 }
11 catch (Exception e)
12 {
13 System.err.println (e);
14 }
15 finally
16 {
17 if (conn != null)
18 {
19 try
20 {
21 conn.close ();
22 System.out.println ("Database connection terminated");
23 }
24 catch (Exception e) { /* ignore close errors */ }
25 }
26 }

however my program keeps bombing at line 7 : Class.forName("com.mysql.jdbc.Driver").newInstance();

when i hit my catch statement i print 'e' and this is my output "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver"

please help

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
laksys
Offline
Joined: 2011-07-18

You put the 'jar' file which contain the drvier class com.mysql.jdbc.Driver in classpath.