Java mysql connectivity
hi
i m trying to connect to mysql database through java. i have mysql-java-connector jars file placed in the JAVA_HOME\jre\lib\ext directory.
now when i try to run this file its starts givin me this error...............
Exception in thread "main" java.lang.NoClassDefFoundError: Test
the java file that im running is this............(Test.java)
import java.sql.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
class Test
public static void main(String args[])
System.out.println("Hello");
System.out.println("Welcome to the world of java");
System.out.println("Lets learn java.");
String url="jdbc:mysql://localhost:3306/database";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String query;
try {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
catch(Exception e)
System.out.println("driver not found"+e.getMessage());
con = DriverManager.getConnection (url, "", "");
stmt = con.createStatement();
query = "select * from test;";
ResultSet result = stmt.executeQuery(query);
while(result.next())
String callNumResult = result.getString("name");
System.out.println(callNumResult);
catch(Exception e)
System.out.println("SQLException caught: " + e.getMessage());
finally {
try {
if (con != null) con.close();
catch (SQLException e) {}
i have also tried adding that mysql-java connector jar file to the classpath........
but all in vain.....the error persists.
plz help me with it.........
ankur
hi
i m trying to connect to mysql database through java.
i have mysql-java-connector jars file placed in the
JAVA_HOME\jre\lib\ext directory.That's a terrible place to put them. Only language extensions (e.g., packages that start with javax) belong in there. Put that JAR closer to your application.
>
now when i try to run this file its starts givin me
this error...............
Exception in thread "main"
java.lang.NoClassDefFoundError: TestLook at the exception: it's complaining about Test, NOT the MySQL JDBC driver class.
You obviously don't understand how CLASSPATH works:
http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/classpath.html
I think you have to add the current directory to the CLASSPATH in order to run your Test:
java -classpath . TestNote the "dot" after -classpath. That tells the class loader to start looking in the current directory. since your Test.java doesn't have a package statement, I'm assuming that Test.class is in the same directory as Test.java.
>
>
>
the java file that im running is
this............(Test.java)
import java.sql.*;
import java.util.*;
import java.net.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
class Test
public static void main(String args[])
System.out.println("Hello");
System.out.println("Welcome to the world of java");
System.out.println("Lets learn java.");
String url="jdbc:mysql://localhost:3306/database";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String query;
try {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
catch(Exception e)
System.out.println("driver not found"+e.getMessage());
con = DriverManager.getConnection (url, "", "");
stmt = con.createStatement();
query = "select * from test;";
ResultSet result = stmt.executeQuery(query);
while(result.next())
String callNumResult = result.getString("name");
System.out.println(callNumResult);
catch(Exception e)
System.out.println("SQLException caught: " +
e.getMessage());
finally {
try {
if (con != null) con.close();
catch (SQLException e) {}
i have also tried adding that mysql-java connector jar
file to the classpath........
but all in vain.....the error persists.
plz help me with it.........
ankur
Similar Messages
-
Hi,
Can anybody tell me how can I make the java-mysql JDBC connection using IDS Server ( type 3 driver )
this is the only driver which bypass proxy/firewall
if any one use this driver before pls give me more information about it.Well, first you have to obtain a type 3 driver for MySQL. I don't know if such a driver exists.
Assuming one does, you'd need a properly configured server.
Once you've got that, the Java code should be identical to that for any other driver. -
Question about Java MySQL connection
Hi guys, greetings to y'all, me name is Ryan, I'm new 'round here.
I have some questions, I have some application that I build with Java and using MSSQL Server 2000 as it's database, and now I want to try to use MySQL as it's database. I use MySQL server 5.0 and Navicat 8 for MySQL for the gateway and Win XP SP2 as my OS, what I want to know is, can you guys give me some connection string example for MySQL, for Java that is, I'm still learning in Java so sorry if I have some mistaken languages or code related words. Thanks a lot guys.
Best Regards.Hi zahid, thanks for the reply, so if I have this code, like this one
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con;
con=DriverManager.getConnection("jdbc:odbc:FlightSource","","");
stat2=con.prepareStatement("insert into Passenger_Table(vPassenger_Name,vPassenger_gender,iPassenger_Age,vPassenger_Destination,vPass_FlightClass,vPass_FlightType,vDate_of_Issue,vDate_of_Departure,vDate_Expire,vForm_Payment,Card_No,vTotal_Price)values(?,?,?,?,?,?,?,?,?,?,?,?)");
stat2.setString(1,textNama.getText());
stat2.setString(2,(String.valueOf(entry2)));
stat2.setString(3,textUmur.getText());
stat2.setString(4,textTujuan.getText());
stat2.setString(5,(String)comboKelas.getSelectedItem());
stat2.setString(6,(String)comboJenisKeberangkatan.getSelectedItem());
stat2.setString(7,(String)comboTglTiket.getSelectedItem()+"/"+texttgltiket1.getText()+"/"+texttgltiket2.getText());
stat2.setString(8,(String)comboTglBerangkat.getSelectedItem()+"/"+texttglberangkat1.getText()+"/"+texttglberangkat2.getText());
stat2.setString(9,(String)comboTglKadaluwarsa.getSelectedItem()+"/"+texttglkadaluwarsa1.getText()+"/"+texttglkadaluwarsa2.getText());
stat2.setString(10,(String)comboPayType.getSelectedItem());
stat2.setString(11,textCardNo.getText());
//stat2.setFloat(12,Float.parseFloat(textHarga.getText()));
stat2.setString(12,textHarga.getText());
stat2.executeUpdate();
JOptionPane.showMessageDialog(null, "The Data has successfully Booked " );
catch(Exception exception)
JOptionPane.showMessageDialog(null,"Error encountered while entering data in the database: "+exception);
}I just simply change the Class.forName{} line right ?
What About the database name, considering in the code above I used ODBC (the ODBC name is FlightSource), so the database was configured when I create the ODBC, then how about MySQL, should I create ODBC too to configured the database that I wanna use ? -
Jar file and remote mysql connect
I have a jar file that i want anyone run it.The problem is that the code makes a connection to a database (mysql) to my computer.How anyone can connect to my databse in my computer from another pc without the user have to had the java \ mysql connect or hte mysql.Only the java.I try with a jnlp file and the jar file stored in my computer.I have a host name and i have open the port 3306 for mysql and allow remote connections to mysql.Can you help me;;
ok i connect to database like this:
try {
String userName = "username";
String password = "password";
String url = "jdbc:mysql://HOSTNAME/bankloans";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
} catch (Exception e) {
System.out.prinln(e);
}The JNPL file
<?xml version="1.0" encoding="Windows-1251"?>
<jnlp
spec="1.0+"
codebase="http://nasikas.ath.cx:8080/bankloans/"
href="BankLoans.jnlp">
<information>
<title>Bank Loans Programme</title>
<vendor>Softlets</vendor>
<description>Bank Loans Programme</description>
<offline-allowed/>
</information>
<security>
<all-permissions/>
</security>
<resources>
<j2se version="1.6+"/>
<jar href="BankLoans.jar" main="true"/>
<jar href="mysql-connector-java-5.1.0-bin.jar"/>
</resources>
<application-desc main-class="Go"/>
</jnlp>What is wrong;; -
Trying to get my java program connected to MySQL
This works perfectly in the Eclipse IDE area that I have but when I run the same program on the Net Beans 3.6 IDE area it gives me a 'not suitable driver' error. To note these are both on the same computer. I would really like to get the Net Beans 3.6 IDE working because that is what I am most familiar with using. If you know of the problem why one IDE area recognizes the driver where the next does not I would sure like to know. Somebody passed the idea that when the 3.6 area is executed there are multiple instances running and it resets the ClassPath(I think they where shooting in the dark but it is a lead none the less). Anyway if anybody has had this problem please enlighten me, Thank-You.
The ClassPath is set to the following:
ClassPath = C:\Program Files\Java\jdk1.5.0_02\lib;C:\unzipped\mysql-connector- java-3.1.7\mysql-connector-java-3.1.7;C:\Program Files
\Java\jdk1.5.0_02\jre\lib\ext;
This is the code:
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect2 {
public static void main(String[] args) {
try {
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception ex) {
System.out.println("HERE");
try {
String url = "jdbc:mysql://localhost/test";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/test", "root", "password");
Statement c = conn.createStatement();
c.execute("insert into green values('richmond')");
c.execute("select * from green");
ResultSet rs = c.getResultSet();
while (rs.next()) {
System.out.println(rs.getString(1));
// Do something with the Connection
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}There are some oddities with the DriverManager when it comes to registering drivers taken from a different ClassLoader, though I don't see how that would apply here, unless the IDE itself is loading one of the classes.
There's a facility in DriverManager to enumerate the registered drivers. It might be worth doing that and seeing their class names. -
Java mysql OK with Terminal but not OK with Apache local web server
With terminal I have :
CLASSPATH=/System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Classes/:/Library/Java/Extensions/:./
SUDO_GID=20
SECURITYSESSIONID=210800
_=/usr/bin/printenv
127:/Library/WebServer/Documents/Java root# java TestMySQL
2006-05-21 13:39:00.0 ************************************************** = OK
127:/Library/WebServer/Documents/Java root#
import java.sql.*;
* mysql-connector-java-3.1.12-bin.jar
* % javac /Library/WebServer/Documents/Java/TestMySQL.java
* % java TestMySQL
public class TestMySQL {
public static void main(String argv[]) throws Exception {
// Load the driver class
Class.forName("org.gjt.mm.mysql.Driver");
1 //Class theClass = null;
2 //try {
3 // theClass = Thread.currentThread().getContextClassLoader().loadClass("org.gjt.mm.mysql.Driver");
4 //}
5 //catch (ClassNotFoundException e) {
6 // theClass = getClass().getClassLoader().loadClass("org.gjt.mm.mysql.Driver");
7 //}
Connection conn = DriverManager.getConnection(
"jdbc:mysql:///test",
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("SELECT now();");
while (rset.next()) {
System.out.println(rset.getString(1));
// Close result set, statement and DB connection
rset.close();
stmt.close();
conn.close();
}I have a simple TestMySQL.html file with applet TestMySQL.class in it.
Nothing but "Applet TestMySQL not inited"
When I uncomment the try/catch lines (lines 1 to 7) , java compiler generate an error... near getClass().getClassLoader().loadClass("org.gjt.mm.mysql.Driver");
With "Class.forName("org.gjt.mm.mysql.Driver");" no problem.
Running MacOS X 10.3.9, Apache/1.3.33 (Darwin) PHP/4.4.1 mod_ssl/2.8.24 OpenSSL/0.9.7i and JVM 1.4.2_09
Thanks for help.
P.S. This my first approach to java/mysql but I would like to see this short program running on my local web server ...
Thanks.hi :-)
can you post the stack trace?
im not sure what is causing the error because of less info,
but have you tried to copy the driver of mysql to tomcat lib folder?
regards, -
MySQL connectivity Problem URGENT plz
Hi
plz can any one help me... its urgent
i need java to connect to MySQL database.with mm.mysql.Driver
the following sample code is just copied from the site and made changes in hostname, dbname and username.
classpath has been given correctly for the mm.mysql.Driver package (mysql.jar).
Thanx in advance....
Result
compilation --> success
while executing i get the following Error.
java.sql.SQLException: General Error: null
at org.git.mm.mysql.connection.<init>(Connection.java)
at org.git.mm.mysql.Driver.connect(Driver.java)
at java.sql.DriverManager.getConnection(DriverManager.java: 515)
at java.sql.DriverManager.getConnection(DriverManager.java: 197)
at JDBCDemoCreate.getConnection(JDBCDemoCreate.java: 36)
at JDBCDemoCreate.<init>(JDBCDemoCreate.java: 14)
java.lang.NullPointerException
at JDBCDemoCreate.<init>(JDBCDemoCreate.java: 17)
at JDBCDemoCreate.main(JDBCDemoCreate.java: 47)
Here is the code. can any one try this !
// JDBCDemoCreate.java
1. import java.util.*;
2. import java.sql.*;
3.
4. public class JDBCDemoCreate {
5.
6. private static final String hostname = "hostname";
7. private static final String port = "3306";
8. private static final String database = "dbname";
9. private static final String username = "username";
10. private static final String password = "";
11.
12. public JDBCDemoCreate() {
13.
14. Connection c = getConnection();
15.
16. try {
17. Statement s = (Statement)c.createStatement();
18. s.executeUpdate("CREATE TABLE rich ( id int primary key, name char(25) )");
19. } catch ( Exception e ) {
20. e.printStackTrace();
21. }
22.
23. }
24.
25. private Connection getConnection() {
26 // Register the driver using Class.forName()
27. try {
28. Class.forName("org.gjt.mm.mysql.Driver").newInstance();
29. } catch ( Exception e ) {
30. e.printStackTrace();
31. }
32.
33. // ask the DriverManager for a connection to the database
34. Connection conn = null;
35. try {
36. conn = DriverManager.getConnection("jdbc:mysql://" + hostname +
37. ":"+ port +"/" + database +
38. "?user=" + username +
39. "&password=" + password );
40. } catch (Exception e) {
41. e.printStackTrace();
42. }
43. return conn;
44. }
45.
46. public static void main( String[] args ) {
47. new JDBCDemoCreate();
48. }
49.}Hi!
You can try with this code coz, i worked with this code only and then i can talk to the database.
Connection con;
Class.forName("org.gjt.mm.mysql.Driver";
con = DriverManager.getConnection("jdbc:mysql:///db?user=root&password=");
Try it out!
Queries regarding this is welcome. Either in this forum itself or u can contact in the mail, the id is
[email protected]
Regards,
dinesh -
JDBC and MySQL connectivity problem
The code i hav attached generates Connectivity exception.. the prob is with the part in bold.. can anyone help
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class testconn {
public static void main(String args[]) {
Connection con = null;
String serverName = "localhost:8080";
String mydatabase = "imagedb";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase; // a JDBC url
String username = "am";
String password = "ta";
try {
Class.forName("com.mysql.jdbc.Driver");
con= DriverManager.getConnection(url, username, password);
if(!con.isClosed())
System.out.println("Successfully connected to " +
"MySQL server using TCP/IP...");
} catch(Exception e) {
System.err.println("Exception: " + e);
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}I had such issue too, and I fixed it by adding in the environment variables the CLASSPATH entry that pointed to all the directories containing the .jar needed for the applications.
for example I used jodbc folder to connect mysql database (I installed last version and I got same issue than yours and it seems to be a 'connector' issue, exactly the same issue than yours) I got something like
CLASSPATH=my root dir/the java dir/the lib dir/jodbc;my root dir/the java dir/other important libs containing .jar files;
This is what I got for the issue, still working around (at the level of mysql all is ok, ...)
Microsoft Windows XP [version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Hurukan>java ConnectJODBC brol
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at ConnectJODBC.main(ConnectJODBC.java:108)
[exception] -- la valeur de 'con' est nulle (DriverManager � retourn� une valeur
nulle)
C:\Documents and Settings\Hurukan>set
APPDATA=C:\Documents and Settings\Hurukan\Application Data
CLASSPATH=c:\Program Files\Java\jdk1.5.0_06\lib;c:\Program Files\Java\jdk1.5.0_06\dev;\c:\Program Files\Java\jdk1.5.0_06\lib\jodbc;
Here is the code that generated this exception
String dburl="jdbc:mysql://127.0.0.1/nosdisques"; // should be next passed by command line
String password="**scrambled**";
String username="**scrambled**";
Connection con=null;
Statement stmt=null;
ResultSet res=null;
String requete="";
String strToWrite="";
// Connexion � la base de donn�e
// Won't work with mysql 5.0.18, mysql connector 3.51.12 is installed [???]
// Previous tests with 5.0.18 were running good, that has started with the last os restoration (and the connector was different of course...)
// tried to retreive older version of the mysql connector
try
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(dburl,username,password);
System.out.println("Nous sommes connect\u201as \u2026 la base " + con.getCatalog());
catch(SQLException sqlex)
System.out.println("[sqlexception]\n");
System.exit(3);
catch(Exception ex)
ex.printStackTrace();
if(con == null)
System.out.println("[exception] -- la valeur de 'con' est nulle (DriverManager \u2026 retourn\u201a une valeur nulle)\n");
System.exit(4);
System.out.println("Impossible to join database, access denied\n");
System.out.println("Verify settings (mysqld or firewall)\n"); System.exit(2);
Maybe the drivers used (last one: connector/j 3.1.12). The .jar file is in the %classpath% directory c:\Program Files\Java\jdk1.5.0_06\lib.
Can't really understand why this code won't run anymore, ...
I took a look on the other computer where the same code is running ok.
These are the differences:
mysql server is 5.0.18 on the other computer the version is 3.23.41
mysql connector is 3.51.12 on the other computer the version is 3.0.10
access rights are the same because the database is the dumped one from 3.23.41 to 5.0.18, and I'm quite good with the dbms management (I'm IT developper in fact, trying to take over java technology ;) )
in this case this is not a sql error but java error.
the jar file is set to the %classpath% folder on both computers
I copied the jar from the other computer, removing the new .jar file and... it failed, exactly the same issue
Still working around, ...
Dimitri -
Dear Fellow Java Developers:
I am a junior java developer and I sincerely apologize for my ignorance. I have searched the archives of this forum for advice and information, and for some reason I am not able to get the results I desire.
I have the following line in my classpath:
C:\mysql\java\mysql-connector-java-2.0.14-bin.jar;.
now when I run the following program which I got of the following url:
http://www.javacoding.net/articles/technical/java-mysql.html?page=1#contentAnchor
/* import needed for JDBC access */
import java.sql.*;
* MySQL Demo Program
* this program is just a little demonstration of the usage
* of MySQL in combination with Java JDBC
* http://www.javacoding.net
public class TestMySQL {
public void test ( String host, String database ) throws Exception {
/* first, we'll test whether the MySQL driver is installed */
testDriver ( );
/* then, we'll get a connection to the database */
Connection con = getConnection ( host, database );
/* we create a table */
executeUpdate ( con, "create table test (id int not null,text varchar(20))" );
/* we insert some data */
executeUpdate(con,"insert into test (id,text) values (1,'first entry')");
executeUpdate(con,"insert into test (id,text) values (2,'second entry')");
executeUpdate(con,"insert into test (id,text) values (3,'third entry')");
/* then we'll fetch this data */
executeQuery ( con, "select * from test" );
/* and we'll destroy the table ... */
executeUpdate ( con, "drop table test" );
/* finally, we close the database */
con.close ( );
* Checks whether the MySQL JDBC Driver is installed
protected void testDriver ( ) throws Exception {
try {
Class.forName ( "org.gjt.mm.mysql.Driver" );
System.out.println ( "MySQL Driver Found" );
} catch ( java.lang.ClassNotFoundException e ) {
System.out.println("MySQL JDBC Driver not found ... ");
throw ( e );
* Returns a connection to the MySQL database
protected Connection getConnection ( String host, String database )
throws Exception {
String url = "";
try {
url = "jdbc:mysql://" + host + "/" + database;
Connection con = DriverManager.getConnection(url);
System.out.println("Connection established to " + url + "...");
return con;
} catch ( java.sql.SQLException e ) {
System.out.println("Connection couldn't be established to " + url);
throw ( e );
* This method executes an update statement
* @param con database connection
* @param sqlStatement SQL DDL or DML statement to execute
protected void executeUpdate ( Connection con, String sqlStatement )
throws Exception {
try {
Statement s = con.createStatement ( );
s.execute ( sqlStatement );
s.close ( );
} catch ( SQLException e ) {
System.out.println ( "Error executing sql statement" );
throw ( e );
* This method executes a select statement and displays the result
* @param con database connection
* @param sqlStatement SQL SELECT statement to execute
protected void executeQuery( Connection con, String sqlStatement )
throws Exception {
try {
Statement s = con.createStatement ( );
ResultSet rs = s.executeQuery( sqlStatement );
while ( rs.next ( ) ) {
String id = ( rs.getObject ("id").toString() );
String text = ( rs.getObject ("text").toString() );
System.out.println ( "found record : " + id + " " + text );
rs.close ( );
} catch ( SQLException e ) {
System.out.println ( "Error executing sql statement" );
throw ( e );
* This one is used to start the program.
public static void main ( String args[] ) throws Exception {
if ( args.length == 2 ) {
new TestMySQL ( ).test ( args[0], args[1] );
} else {
System.out.println ( "usage: java TestMySQL host database" );
when I compile and run the program, I still get a java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
I get the same error when I use the following driver as well
org.gjt.mm.mysql.Driver
Does my java program have to be in a certain directory in relation to the mysql directory? All I did at the msql> prompt was to create a database called jtest and typed in
C:\java TestMySQL localhost jtest
in order to run the above program.
Am I overlooking something? Have I forgotten to do something? I am currently using jdk1.3 instead of jdk1.4, is that the problem?? If it is, how do I correct the problem without switching to jdk1.4??
Any and all help is appreciated, and I sincerely thank all developers who read this post.
Take care.
Sincerely;
Fayyazsyedfa,
I don't know if you have already figured out the problem that you were experiencing, but I was having this same problem, and I finally got it figured out. I was having difficulty on how exactly to set the classpath. I am using Windows XP, and I have seen and tried a lot of different variations. From the command prompt in the directory where the file was saved I finally got your program to compile using:
java -classpath C:\mysql\mysql-connector-java-2.0.
14\mysql-connector-java-2.0.14-bin.jar; TestMySQL localhost test
Of course it would be much easier if the environment variable for this was set so you don't have to type it in everytime at the command prompt, and I finally got that one figured out to. If you are using Windows XP then you can:
Right click on My Computer and go to Properties.
Click on Advanced.
Click on Environment Variables.
Under System Variables, click on New.
For the Variable name type: CLASSPATH
For the Variable Value type: .;C:\mysql\mysql-connector-java-2.0.14\mysql-connector-java-2.0.14-bin.jar
In the above variable value, the ".;" before C: isn't a typo. The path that I put in is the path to the MySQL JDBC driver on my computer so it may vary on your computer.
I think this will also work with Windows 2000.
I hope this helps if you still need it, maybe it will also help somebody else with the same problem. -
Auto mySQL connectivity(Username and Password)
Hey guys!
Good Day!
I have something to ask if possible to java and mySQL connectivity.
I have project that connects to mysql but im using this:
"+con1 = DriverManager.getConnection("jdbc:mysql://localhost/POS_Database","root", "12345");+"
Now, how to auto config the mysql connection not setting the username and password in the project? It configure whatever the settings of mySQL (username and password).you will have to have the user name and password someware. If not in the code. You casn put them in a file and read it in the code.
Another thing that you can do is to make every user account of your software a valid user in the database. So when the user logs in to software users user name and the password is what you have to use to connect to database. But that will create a bit of a administrative overhead and also it will make it deficult to use connection pooling. -
JDBC Java- mysql problem help!
Hi, I wnat to connect to mySQL fromo Java, I followed all the instructions from the mySql web page, yet I havent been able to do it, when I compile the java progrm I keep getting class not found exceptions, I am using Fedora Core and Java was already installed-well I chose to install it when I installed the operating system, the point is that the paths are all assigned by he system not by me.
WHat can I do?, Ive been trying over andover again with no results, hopefully somebody can help, I tried to include all the configuration in this email,
thank you
my java program is the following:
t.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class t {
public static void main (String[] args) {
System.out.println("Hello, world!\n");
Class.forName("com.mysql.jdbc.Driver");
when I javac t.java
I have the following error
4. ERROR in t.java
(at line 11)
Class.forName("com.mysql.jdbc.Driver");
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Unhandled exception type ClassNotFoundException
when I comment out the Class.forName the hello world rogram runs fine
when I vi /etc/java java.conf this is the result
# System-wide Java configuration file -- sh --
# JPackage Project [www.jpackage.org]
# Location of jar files on the system
JAVA_LIBDIR=/usr/share/java
# Location of arch-specific jar files on the system
JNI_LIBDIR=/usr/lib/java
# Root of all JVM installations
JVM_ROOT=/usr/lib/jvm
# You can define a system-wide JVM root here if you're not using the default one#JAVA_HOME=$JVM_ROOT/java-gcj
# Options to pass to the java interpreter
JAVACMD_OPTS=
~
[root@localhost test]# echo $PATH
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/bin
echo $JAVA_HOME
it contains nothing
ls /usr/share java*
java
java-1.3.0
java-1.4.0
java-1.4.1
java-1.4.2
java-1.5.0
javadoc
java-ext
java-utils
mysql-connector-java-3.1.13-bin.jar is under
/usr/share/java
in /etc/profile I have:
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-3.1.13-bin.jar
in /root/.bash_profile i have
CLASSPATH=/usr/share/java/mysql-connector-java-3.1.13-bin.jar:/usr/lib/java-ext/mysql-connector/mysql-connector-java-3.1.13-bin.jar
export CLASSPATH
when I echo $PATH i have
/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/usr/X11R6/bin:/root/binThanks duff,
The driver seems to be found
when I run
public class t {
public static void main (String[] args) {
try
System.out.println("Hello, world!\n");
Class.forName("com.mysql.jdbc.Driver");
System.out.println("MySQL Driver Found");
catch (ClassNotFoundException e)
System.out.println("MySQL Driver NOT Found");
e.printStackTrace();
I feel somehow ive been focusing in the wrong side of the problem due to my ignorance in Java. Please help me to understand, the reson for which ithe runtime was telling me that there was an unhandled exception was because it is a requirement to handle all exceptions of this kind? why wouldnt it cmplain if I jst did the hello world without any exception handling, maybe because it is a requirement in the Class.forName...
the other question is, is the message I was obtaining completely independent of the fact that the class was or was not found?
Maybe, I should go with these questions to the newbies forum...
thanks -
How we build Java Database Connectivity for Oracle 8i Database
Can any one send me a sample code for Java Database Connectivity for Oracle 8i Database
it will be a grat help
Thanks & Regards
RasikaYou don't need a DSN if you use Oracle's JDBC driver.
You didn't read ANY of the previous replies. What makes you think this one willk help? Or any instruction, for that matter?
Sounds like you just want someone to give it to you. OK, I'll bite, but you have to figure out the rest:
import java.sql.*;
import java.util.*;
* Command line app that allows a user to connect with a database and
* execute any valid SQL against it
public class DataConnection
public static final String DEFAULT_DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DEFAULT_URL = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:\\Edu\\Java\\Forum\\DataConnection.mdb";
public static final String DEFAULT_USERNAME = "admin";
public static final String DEFAULT_PASSWORD = "";
public static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
public static final String DEFAULT_URL = "jdbc:mysql://localhost:3306/hibernate";
public static final String DEFAULT_USERNAME = "admin";
public static final String DEFAULT_PASSWORD = "";
/** Database connection */
private Connection connection;
* Driver for the DataConnection
* @param command line arguments
* <ol start='0'>
* <li>SQL query string</li>
* <li>JDBC driver class</li>
* <li>database URL</li>
* <li>username</li>
* <li>password</li>
* </ol>
public static void main(String [] args)
DataConnection db = null;
try
if (args.length > 0)
String sql = args[0];
String driver = ((args.length > 1) ? args[1] : DEFAULT_DRIVER);
String url = ((args.length > 2) ? args[2] : DEFAULT_URL);
String username = ((args.length > 3) ? args[3] : DEFAULT_USERNAME);
String password = ((args.length > 4) ? args[4] : DEFAULT_PASSWORD);
System.out.println("sql : " + sql);
System.out.println("driver : " + driver);
System.out.println("url : " + url);
System.out.println("username: " + username);
System.out.println("password: " + password);
db = new DataConnection(driver, url, username, password);
System.out.println("Connection established");
Object result = db.executeSQL(sql);
System.out.println(result);
else
System.out.println("Usage: db.DataConnection <sql> <driver> <url> <username> <password>");
catch (SQLException e)
System.err.println("SQL error: " + e.getErrorCode());
System.err.println("SQL state: " + e.getSQLState());
e.printStackTrace(System.err);
catch (Exception e)
e.printStackTrace(System.err);
finally
if (db != null)
db.close();
db = null;
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection() throws SQLException,ClassNotFoundException
this(DEFAULT_DRIVER, DEFAULT_URL, DEFAULT_USERNAME, DEFAULT_PASSWORD);
* Create a DataConnection
* @throws SQLException if the database connection fails
* @throws ClassNotFoundException if the driver class can't be loaded
public DataConnection(final String driver,
final String url,
final String username,
final String password)
throws SQLException,ClassNotFoundException
Class.forName(driver);
this.connection = DriverManager.getConnection(url, username, password);
* Get Driver properties
* @param database URL
* @return list of driver properties
* @throws SQLException if the query fails
public List getDriverProperties(final String url)
throws SQLException
List driverProperties = new ArrayList();
Driver driver = DriverManager.getDriver(url);
if (driver != null)
DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
if (info != null)
driverProperties = Arrays.asList(info);
return driverProperties;
* Clean up the connection
public void close()
close(this.connection);
* Execute ANY SQL statement
* @param SQL statement to execute
* @returns list of row values if a ResultSet is returned,
* OR an altered row count object if not
* @throws SQLException if the query fails
public Object executeSQL(final String sql) throws SQLException
Object returnValue;
Statement statement = null;
ResultSet rs = null;
try
statement = this.connection.createStatement();
boolean hasResultSet = statement.execute(sql);
if (hasResultSet)
rs = statement.getResultSet();
ResultSetMetaData meta = rs.getMetaData();
int numColumns = meta.getColumnCount();
List rows = new ArrayList();
while (rs.next())
Map thisRow = new LinkedHashMap();
for (int i = 1; i <= numColumns; ++i)
String columnName = meta.getColumnName(i);
Object value = rs.getObject(columnName);
thisRow.put(columnName, value);
rows.add(thisRow);
returnValue = rows;
else
int updateCount = statement.getUpdateCount();
returnValue = new Integer(updateCount);
finally
close(rs);
close(statement);
return returnValue;
* Close a database connection
* @param connection to close
public static final void close(Connection connection)
try
if (connection != null)
connection.close();
connection = null;
catch (SQLException e)
e.printStackTrace();
* Close a statement
* @param statement to close
public static final void close(Statement statement)
try
if (statement != null)
statement.close();
statement = null;
catch (SQLException e)
e.printStackTrace();
* Close a result set
* @param rs to close
public static final void close(ResultSet rs)
try
if (rs != null)
rs.close();
rs = null;
catch (SQLException e)
e.printStackTrace();
* Close a database connection and statement
* @param connection to close
* @param statement to close
public static final void close(Connection connection, Statement statement)
close(statement);
close(connection);
* Close a database connection, statement, and result set
* @param connection to close
* @param statement to close
* @param rs to close
public static final void close(Connection connection,
Statement statement,
ResultSet rs)
close(rs);
close(statement);
close(connection);
}% -
Help with mySQL Connection string
Here is hoping someone can help & once I get it down I promise I'll post all my work on this list so some other newbie can benefit.
I'm simply trying to run a very very straightforward JDBC test with mySQL & I keep getting the "Server configuration denies access to data source" error. But before you tell me that I must simply look at what my mysql.db & mysql.user table allows - I'VE TRIED THAT. I realize that the error is probably there somewhere - but I can't see it.
I've tried connecting with 2 different accounts - the provided "root" & a user I created "deep" to 2 different databases the provided "test" & "testdb" which I created) . Here is what mysql says about the two different databases
mysql> select * from db;
Host | Db | User |.......
-----+------------+-------
| % | test | | ......
| % | test\_% | | ........
| localhost | testdb | deep |........Note that "root" should have access to "test" & deep@localhost should have access to "testdb" right?
So here are all the connection strings I have tried - all return the same error below
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "mypass"
// "jdbc:mysql://localhost:3306/testdb", "deep", "mypass"
// "jdbc:mysql://localhost/testdb?user=deep&password=mypass"
// "jdbc:mysql://localhost/testdb", "deep", "mypass"
// "jdbc:mysql://localhost:3306/testdb?user=deep@localhost&password=mypass"
// "jdbc:mysql://localhost:3306/testdb?user=deep&password=mypass"
// "jdbc:mysql://localhost/testdb", "deep@localhost", "mypass"
// "jdbc:mysql:///test", "root", "mypass"
// "jdbc:mysql://localhost/test", "root@localhost", "mypass"
);My Error:
Exception in thread "main" java.sql.SQLException: Server configuration denies access to data source
at org.gjt.mm.mysql.MysqlIO.init(MysqlIO.java:193)
at org.gjt.mm.mysql.Connection.connectionInit(Connection.java:261)
at org.gjt.mm.mysql.jdbc2.Connection.connectionInit(Connection.java:89)
at org.gjt.mm.mysql.Driver.connect(Driver.java:167)
at java.sql.DriverManager.getConnection(DriverManager.java:517)
at java.sql.DriverManager.getConnection(DriverManager.java:199)
at TestMySQL4.main(TestMySQL4.java:76)BTW:
I am using MacOSX 10.1
MySQL 3.23.42
The driver is: mm.mysql-2.0.6.jar
Please help!
'deephi amandeep
well i m getting the same error message when trying to connect MYSQL using mm.jdbc driver.
java.sql.SQLException : Server configuration denies access to data base source.
query.jdbcDriver org.gjt.mm.mysql.Driver
query.databaseURL jdbc:mysql://aaa.bbb.com/pluto
query.databaseUserName samin
query.databasePwd samin
query.summaries true
i hve installed mysql on server aaa.bbb.com network 1
and trying to run application on network 2
Thanks
samir -
Tomcat 6/Java/mySql: Data source name not found
I installed the following on my laptop which has a Windows 2000 operating system:
- ODBC Connector for mySql
- the MySql Connector/J for Java
ODBC
In the Data Source ODBC Administrator of the Control panel I added a Data Source name for the mySql Database:
Data Source Name: mysql
Server: localhost
Database: mysql
When I click the Test button I get the message: Success; Connection was made!
TOMCAT
C:\apache-tomcat-6.0.18
I copied mysql-connector-java-5.0.8-bin.jar into:
- the lib folder
- the lib folder under webapps>WEB-INF\testapp
I added the above paths to CLASSPATH
TOMCAT SERVER.XML
In the server.xml file under the CONF folder I entered
<Context path="/testapp" docBase="testapp" debug="0"
reloadable="true" crossContext="true">
<Resource name="jdbc/mysql"
auth="Container"
type="javax.sql.DataSource"
description="The connection pool will be bound into JNDI with the name
java:/comp/env/jdbc/MySQLDB">
</Resource>
<ResourceParams name="jdbc/mysql">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>10</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>5</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
<parameter>
<name>password</name>
<value>test</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost/mysql</value>
</parameter>
</ResourceParams>
</Context>
However, when I try to run a java servlet, I am getting the following error:
SqlException: Could not connect to database
[ODBC Driver Manager] Data source name not found and no default driver specified
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(“jdbc:mysql://localhost/mysql”, strUserId, strPassword);
MySql is actually installed on c:\Program Files\MySql\Mysql 5.0
What am I missing? How can I get the mySql connection to work?
Thanks,
RobinYou seem to be specifying JDBC driver while you are trying to connect to your database using ODBC,
RobinHR wrote:
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
and ,
RobinHR wrote:
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(jdbc:mysql://localhost/mysql, strUserId, strPassword);
*********************You would be using "sun.jdbc.jdbcodbc.Driver" rather!
Refer MySQL sample examples/documentation on how to connect to your database using ODBC
And this on how to create a DSN
Edited by: anamupota on Jan 16, 2009 8:27 AM -
i'm using CFMX , mysql 5.0 , mysql-connector-java-3.1.13
how do i set the connection...
1) do i need to add the driver into the ODBC ?
2) do i need to set the COLD FUSION ADMINISTRATOR ? how to
set?
3) i had try to unzip the mysql connecter then paste into the
C:\CFusionMX7\wwwroot\WEB-INF\lib is it correct?
4) how can get some solution here.
tjxI came across this older post. I have the same problem. I
have followed the instruction, and tried different versions of the
driver, but the error still comes up when I try to connect through
CFMX7:
"Connection verification failed for data source: MySQL_test
java.sql.SQLException: No suitable driver available for
MySQL_test, please check the driver setting in resources file,
error: null
The root cause was that: java.sql.SQLException: No suitable
driver available for MySQL_test, please check the driver setting in
resources file, error: null"
If I can add any additional information so that someone can
help me diagnose the problem, please let me know.
Maybe you are looking for
-
The requested URL /apex/f was not found on this server
Hi! In my project I've rebuilt a lengthy process on a page being used for months. I tested it thoroughly at home on APEX 2.2/Windows. Today I imported the project at my customer on APEX 2.1/Linux and trying to open this page I get the above error mes
-
Unknown error while trying to build and test web service
Hi, I get this error while building my web service.It says "An unexpected exception occurred while attempting to process the classes and annotations for this Web Service. Error: Unknown KNEX string: description.null" Pasted below is the output on the
-
Should I use Borlands Basic Wizard class?
Hi, I am just about to start programming a wizard for my Swing application. I am using Borland JBuilder as an IDE and in the help file found a class called "Basic Wizard". Is this not an official class? If the answer is yes, is it advisable to use th
-
My Creative Cloud App shows that I have Acrobat XI installed on my system but it's not on my system. I have had to uninstall it 3 times in the last 4 days as it keeps asking me to continue with a Free Trial or buy the program. I am already a subscrib
-
Same 8 updates after OS X Reboot
Hi there, I am using OS X Mavericks and everything seems to be working great. I only have one thing that bugs me and it's when I restart my Mac I get the same 8 updates on Creative Cloud. Even after running the update, shutting down the Computer when