Java with MYSQL in Linux

i am using JSP in Linux Platform. when i connected to mysql with mysql driver for odbc by using the following code,
import java.sql.*;
public class TestMysql
public static void main(String args[]) {
try {
          Connection con;
          String connStr = "jdbc:mysql://localhost/test?user=root&password=mysql";
          Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
          System.out.println("OK");
          con = DriverManager.getConnection( connStr );
          System.out.println("Again OK");
catch( Exception x )
x.printStackTrace();
i got the following exception
OK
java.sql.SQLException: Error during query: Unexpected Exception: java.io.CharConversionException message given: null
Nested Stack Trace:
** BEGIN NESTED EXCEPTION **
java.io.CharConversionException
STACKTRACE:
java.io.CharConversionException
at gnu.gcj.convert.Input_iconv.read(char[], int, int) (/usr/lib/libgcj.so.5.0.0)
at java.lang.String.init(byte[], int, int, java.lang.String) (/usr/lib/libgcj.so.5.0.0)
at java.lang.String.String(byte[], int, int, java.lang.String) (/usr/lib/libgcj.so.5.0.0)
at com.mysql.jdbc.SingleByteCharsetConverter.SingleByteCharsetConverter(java.lang.String) (Unknown Source)
at com.mysql.jdbc.SingleByteCharsetConverter.initCharset(java.lang.String) (Unknown Source)
at com.mysql.jdbc.SingleByteCharsetConverter.getInstance(java.lang.String, com.mysql.jdbc.Connection) (Unknown Source)
at com.mysql.jdbc.Connection.getCharsetConverter(java.lang.String) (Unknown Source)
at com.mysql.jdbc.StringUtils.getBytes(java.lang.String, java.lang.String, java.lang.String, boolean, com.mysql.jdbc.Connection) (Unknown Source)
at com.mysql.jdbc.Buffer.writeStringNoNull(java.lang.String, java.lang.String, java.lang.String, boolean, com.mysql.jdbc.Connection) (Unknown Source)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(com.mysql.jdbc.Statement, java.lang.String, java.lang.String, com.mysql.jdbc.Buffer, int, com.mysql.jdbc.Connection, int, int, boolean, java.lang.String, boolean) (Unknown Source)
at com.mysql.jdbc.Connection.execSQL(com.mysql.jdbc.Statement, java.lang.String, int, com.mysql.jdbc.Buffer, int, int, boolean, java.lang.String, boolean, boolean) (Unknown Source)
at com.mysql.jdbc.Connection.configureClientCharacterSet() (Unknown Source)
at com.mysql.jdbc.Connection.initializePropsFromServer() (Unknown Source)
at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Properties, java.lang.String, java.lang.String) (Unknown Source)
at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Properties) (Unknown Source)
at java.sql.DriverManager.getConnection(java.lang.String, java.util.Properties) (/usr/lib/libgcj.so.5.0.0)
at java.sql.DriverManager.getConnection(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
at TestMysql.main(java.lang.String[]) (Unknown Source)
** END NESTED EXCEPTION **
at com.mysql.jdbc.Connection.execSQL(com.mysql.jdbc.Statement, java.lang.String, int, com.mysql.jdbc.Buffer, int, int, boolean, java.lang.String, boolean, boolean) (Unknown Source)
at com.mysql.jdbc.Connection.configureClientCharacterSet() (Unknown Source)
at com.mysql.jdbc.Connection.initializePropsFromServer() (Unknown Source)
at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Properties, java.lang.String, java.lang.String) (Unknown Source)
at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Properties) (Unknown Source)
at java.sql.DriverManager.getConnection(java.lang.String, java.util.Properties) (/usr/lib/libgcj.so.5.0.0)
at java.sql.DriverManager.getConnection(java.lang.String) (/usr/lib/libgcj.so.5.0.0)
at TestMysql.main(java.lang.String[]) (Unknown Source)
i have the database, hello.
The same code works well in Windows, But in Linux, the above exception.
By using the username root and password mysql , i can connect to mysql directly from the mysql prompt.
Pls help me..
I have already put the query 'access denied problem in Mysql' some day before. from the reply, i made some changes in user table(ie. set the password for [email protected].).After this change, this new Exception came..
The structure of my mysql.user table is
#     host                         user          password
1     localhost                    root          68d4f47c49a579c9
2     localhost.localdomain          root          68d4f47c49a579c9
3     localhost.localdomain          
4     localhost          
Pls help me.
Edited by: SUMESHBABU_R on Sep 30, 2007 11:36 PM

Well, at least the trace tells me that this issue is to be tracked back to the core of the MySQL JDBC driver and the Linux's implementation of JVM. It might be worth the effort to post this issue at their website/forum/issuetracker. It might also be worth the effort to tryout the newer MySQL JDBC driver 5.1, as it is written specific for JDK 6.0 (while MySQL JDBC driver 5.0 is targeted at JDK 5.0).

Similar Messages

  • Can' t connect Java with MySQL

    My goal is to connect Java with MySQL. I found many solutions on Internet, but I always get the same mistake:
    SQLException: No suitable driver
    SQLState: 08001
    VendorError: 0MySQL works fine alone or with php.Only thing left me to think is that the installed versions are not compatible for this mysql-connector-java-5.0.4
    I don't believe that could be a reason.
    Installed versions are:
    Apache Tomcat 5.5.20 Server
    Apache HTTP Server 2.2.4
    PHP 5.2.0
    MySQL 5.2
    jre 1.5.0_11
    jdk1.5.0_11
    Apache Tomacat JK2 connector Version: 1.2.20 File Name: mod_jk-apache-2.2.3.so
    mysql-connector-java-5.0.4
    I also set connector in class path: C:\mysql-connector-java-5.0.4;C:\mysql-connector-java-5.0.4\mysql-connector-java-5.0.4-bin.jar;C:\mysql-connector-java-5.0.4\src\com\mysql\jdbc
    For installation I used manulas from:
    http://apacheguide.org/jsp.php
    http://doc.51windows.net/mysql/?url=/MySQL/ch23s03.html
    Here is also a test code in java:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
       public class Connect
           public static void main (String[] args)
               Connection conn = null;
               try {
        conn =
           DriverManager.getConnection("jdbc:mysql://localhost/first_test" +
                                       "user=monty&password=greatsqldb");
        // 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());
       }i'm desperate, please help or tell me someone who'll know the answer.
    Thank You in advance

    hey buddy .. it seems yr code is wrong .. in getconnection () method u should also specify the port ,which u r not doing ...
    the default port for MySQL is 3306 ... see below i am giving you a sample code ... its working fine .. and dont forget to put the MySQL driver jar path in to classpath and also copy the jar into common/lib folder of your tomcat ....
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    public class MySQLConnectionTest {
         public static void main(String[] args) {
    new MySQLConnectionTest().connTest();
    public void connTest() {
              String tableName = "portfolio"; //change as per setting
              String hostName = "10.81.9.39"; // please change for the target database ip or hostname
              String dbPort = "3306"; //change if not using the default
              String dbName = "tradingsystem"; //change as per the given DB name
              String username = "root"; //change as per setting
              String password = "password"; //change as per setting
              System.out.println("before try");
              Double data=0.0;
         Double data1=0.0;
              try {
    Class.forName("org.gjt.mm.mysql.Driver");
                   System.out.println("before driver manager");
    Connection conn = DriverManager.getConnection("jdbc:mysql://"+hostName+":"+dbPort+"/"+dbName, username, password);
    String query1 = "select * from "+tableName+" where User_id='trader1' and Stock_Type='Equity'";
    System.out.println("quesry1="+query1);
    Statement stmt = conn.createStatement();
    ResultSet rs1 = stmt.executeQuery(query1);
    while(rs1.next())
         System.out.println("hiiiiii for rs1");
         System.out.println(rs1);
         Quantity=(Integer)rs1.getObject(5);
         MarketPrice=(Double) rs1.getObject(8);
         data=Quantity*MarketPrice;
         data1+=data;
         System.out.println("data1="+data1);
         i=0;
    rs1.close();
    stmt.close();
    conn.close();
    } catch (ClassNotFoundException e) {
    e.printStackTrace(System.err);
    } catch (SQLException e) {
    e.printStackTrace(System.err);
    i hope it will work for u...
    cheers,

  • Date Problem in Java with MySql

    Hello
    I am using Java with Mysql.I want to enter date in some in my format(YYYY:MM:DD:HH:MM:SS), this thing i have convert using format class and format class return date in String and iwwnat to insert this value in MySQL Table,So i want to know how can i convert String value in Date for Mysql is their inbuild function for converting string into date in mysql.
    Regards
    Anupam S

    Use PreparedStatement and SimpleDateFormat classes
    http://onesearch.sun.com/search/onesearch/index.jsp?qt=%2BPreparedStatement+%2BSimpleDateFormat+&qp=siteforumid%3Ajava48&chooseCat=allJava&col=developer-forums&site=dev

  • Hoe to connect java with mysql 5.0

    I have installed the new Os. in that RHE-5 Os is there, now I want that java can connect ot mysql but , its not able connect with mysql so please guide me.

    1) download mysql connector/J JDBC driver from mysql.com
    2) put the driver jar somewhere where you can put it in the classpath of your application
    3) use proper setup code to connect to the database (search google, tons of examples)
    If at any step you have no clue what I am talking about, you need a good book to help you further.

  • Problems conecting java with mysql

    Hi, im workin' with mysql-connector-java-3.1.12 and it work on debug runtime but not when i access the .jar of the project.
    the code of conection is:
    try
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection(url,login,password);
    con.setAutoCommit(false);
    catch (Exception e)
    JOptionPane.showMessageDialog(null,"error en " + e.getMessage());
    there is no problems with code, it works!!, but i don't know what to do about of conection in the .jar
    I apreciate some help with this, Thankkkssss!!!

    Hi, im workin' with mysql-connector-java-3.1.12 and
    it work on debug runtime but not when i access the
    .jar of the project.Huh?
    the code of conection is:
    try
    lass.forName("com.mysql.jdbc.Driver").newInstance();
    con =
    DriverManager.getConnection(url,login,password);
    con.setAutoCommit(false);This is probably wrong. Unnecessary in this case - you aren't doing any writes.
    catch (Exception e)
    OptionPane.showMessageDialog(null,"error en " +
    e.getMessage());This is foolish code. You don't need Swing or a dialog box. You're printing less information than is available. Better to print the entire stack trace.
    is no problems with code, it works!!, Plenty of problems, really, regardless of whether it "works".
    You don't post your URL. That would help.
    but i don't
    know what to do about of conection in the .jar
    I apreciate some help with this, Thankkkssss!!!Put in the CLASSPATH, of course. NOT a system environment variable, either. javac.exe and java.exe ignore it. Use the -classpath option.
    %

  • Connectivity java with mySql

    Hi
    Can any one tell me how should i connect my java application with mySql database here is the small code which i written.
    import java.sql.*;
    class tryjdbc
         public static void main(String[] args) throws Exception
         try
              Class.forName("com.mysql.jdbc.Driver").newInstance();
              String connectionURL = "jdbc:mysql://localhost:3306/learn?user=root;password=";
              Connection connection = DriverManager.getConnection(connectionURL, "root", "");
              Statement statement = connection.createStatement();
              ResultSet rs = statement.executeQuery("Select ecode from emp");
              while (rs.next())
                   System.out.println(rs.getString("ecode"));
              catch (Exception e){
                   System.out.println(e);
    Can any one please tell me the error there is no eror in compiling but at run time it gives error
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
    Thanks in advance
    Dhiraj

    Hi Dhiraj,
    String connectionURL = "jdbc:mysql://localhost:3306/learn?user=root;password=";
    Connection connection = DriverManager.getConnection(connectionURL, "root", "");
    It seems to be your trying to pass twice of your properties details. One from through URL and another from by pasing the parameters on getConnection() method. Better to avoid to use two place in same application. and one more thing I want to confirm r u using "stable" Driver or "alpha" Driver.
    Raju

  • JAVA with MYSQL problem

    i am using jdk1.6.0_02,apache tomcat 5.5.23 ,mysql integrated with redhat linux EE 4 and.mysql connector java 5.0.7.bin.jar.
    look at the the following java program
    import java.sql.*;
    public class TestMysql
    public static void main(String args[])
    try
    String driver = "com.mysql.jdbc.Driver";
    Class.forName( driver );
    String url = "jdbc:mysql://localhost/test";
    DriverManager.getConnection( url, "root", "mysql" );
    catch( Exception x )
    {      x.printStackTrace();
    i got the following exception
    java.sql.SQLException: Access denied for user 'root'@'localhost.localdomain' (us *** password:
    YES)
    at com.mysql.jdbc.SQLError.createSQLException(java.lang.String, java.lang.Str ***, int)
    (Unknown Source)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(int) (Unknown Source)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket() (Unknown Source)
    at com.mysql.jdbc.MysqlIO.secureAuth411(com.mysql.jdbc.Buffer, int, java.lang .String,
    java.lang.String, java.lang.String, boolean) (Unknown Source)
    at com.mysql.jdbc.MysqlIO.doHandshake(java.lang.String, java.lang.String, jav a.lang.String)
    (Unknown Source)
    at com.mysql.jdbc.Connection.createNewIO(boolean) (Unknown Source)
    at com.mysql.jdbc.Connection.Connection(java.lang.String, int, java.util.Prop erties,
    java.lang.String, java.lang.String) (Unknown Source)
    at com.mysql.jdbc.NonRegisteringDriver.connect(java.lang.String, java.util.Pr operties)
    (Unknown Source)
    at java.sql.DriverManager.getConnection(java.lang.String, java.util.Propertie s)
    (/usr/lib/libgcj.so.5.0.0)
    at java.sql.DriverManager.getConnection(java.lang.String, java.lang.String, j
    ava.lang.String) (/usr/lib/libgcj.so.5.0.0)
    at Connect.main(java.lang.String[]) (Unknown Source)
    access denied problem. but the user name and password are correct. i can login to mysql by using
    the same username and password.
    but when connecting through java , i can't ? what is the problem?
    can u help me.?
    actually i am working in JSP. and when i got this problem, i created a small java program for testing.
    here i am submitting the java program.

    friend please put your code inside
       // your code goes here  it will more readable and other can solve it better.
    ==================
    and your problem tells that you must set access permission inside
    mySQL server.
    or try with creating new User with password.
    EnJOY.
    Ghanshyam
    Edited by: Ghanshyam on Sep 28, 2007 4:13 PM

  • How make installer java with mySQL database

    How do I create a java installer for windows, because I have a project that uses mySQL database.
    Anyone please help me....

    If you have eg. a desktop application which needs a database, but don't have/ need a database server, which is accessed by several instances of the application (which seems to be the case, otherwise you wouldn't want to install it along with the application), consider an embedded database such as Apache Derby/ Java DB.
    Then all you need is to ship some jars and make sure they are on the classpath.
    If you're using JPA and generate the DB schema, then switching DB vendors should be quite easy. Just reconfigure your persistence.xml.

  • JSP with MYSQL on linux and windows2k

    I am using a linux box as a web server with tomcat and mysql. I aslo have a mirror on a Win2k machine running the same environment.
    I have a jsp file that uses a bean to update the database and it works on the win2k environment but not linux.
    In windows I see error messages in the tomcat console, how do I see these message on linux?
    Thank you,
    Paul.

    Did you check ALL of the files?
    There are files named "localhost_log.TODAYSDATE.txt", there are files named "catalina_log.TODAYSDATE.txt", and there's a file called "catalina.out".
    "catalina.out" appears to contain information very similar to the DOS output screen on the Windows platform.
    If those files don't have what you're looking for, then you'll have to get help from someone with more expertise than myself!

  • Need help on java with mysql...

    I want to make application that will use mysql as database. I have downloaded mysql connector j but i'm confuse about how to install it to jdk. for reference, i'm using windows xp, phptriad that have mysql 4.1.
    After that, how do I connect my application to the database?
    please help...
    Thanks before...

    Have a look at this tutorial:
    http://java.sun.com/docs/books/tutorial/jdbc/index.html

  • Java with mysql

    if two tables r given, i want a code which should tell tat ,in which table foreign key is available.
    so please kindly help out in this problem.
    is there is any query or code avalible to find out which table as foreign key.

    I don't know if this will have what you're looking for, but that kind of information is available with [url http://java.sun.com/j2se/1.5.0/docs/api/java/sql/DatabaseMetaData.html]DatabaseMetaData. You get it with [url http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Connection.html#getMetaData()]Connection.getMetaData().
    If you're not familiar with JDBC, see this tutorial:
    http://java.sun.com/developer/onlineTraining/Database/JDBC20Intro/

  • Using java with mysql JDBC

    Hello
    I'm trying to write a program which reads in tab-delimeted text files and then stores the results in a mysql database. The files are roughly 20,000 lines long and can have up to 10 columns, so for the biggest files I have 200,000 pieces of data to be stored seperately in the database.
    I'm currently using the readLine() method of bufferedreader, then using the split function to seperate the string into tokens. The problem is that it seems to be very slow. It is a lot of information, and im not running it on a very fast machine, but even so im sure there must be a more efficient way of acheiving this.
    Here's some of my code:
    BufferedReader in = new BufferedReader(new FileReader("test.res"));
    while((result = in.readLine()) != null) {
    result = in.readLine();
    aLine = result.split("\t");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[0] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[1] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[2] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[3] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[4] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[5] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[6] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[7] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[8] +"')");
    stmt.executeUpdate("INSERT INTO test(words)" + "values('" + aLine[9] +"')");
    I would appreciate any advice thanks.
    PS this is the first time ive tried anything like this so im probably missing something obvious.

    Form the example you have chosen it seems to me, that your table only has one column (words) and that you have multiple value entries for that column in one line of your text file ?!
    That is strange. Normaly I would assume (like the other answers indicate) that you have several columns and that each line in your text file has n values each for a different column.
    Have look at PreparedStatement.
    // the name of your connection is con, you have six columns named col1 to col6 and six entries per line, All six are strings...
    PreparedStatement pstmt = con.prepareStatement("insert into test (col1 , col2 , col3,col4,col5,col6) values( ? , ? , ? , ? , ? , ?)") ;
    BufferedReader in = new BufferedReader(new FileReader("test.res"));
    while((result = in.readLine()) != null) {
       result = in.readLine();
       aLine = result.split("\t");
       for (int i = 0 ; i < 6 ; i++) {
           pstmt.setString((i+1),aLine) ;
    pstmt.executeUpdate() ;
    But this is still not the fastest approach. MySQL supports bulk imports
    Have look at this feature. Maybe the fastest way is to 'convert' the textfile into something like a MySQL dump an than process it using it the MySQL import features.

  • Java connectivity with db2 in linux

    hi all,
    i wish to know how to connect java with db2 in linux.actually which is the string that is to be included in the following:
    class.forName("//which is the string that is to be included here");
    Connection con("jdbc:????");

    hi all,
    i wish to know how to connect java with db2same as every other database and OS. JDBC is the way.
    in linux.actually which is the string that is to be
    included in the following:
    lass.forName("//which is the string that is to be
    included here");full name of the DB2 JDBD driver class.
    Connection con("jdbc:????");look at the docs for your JDBC driver to figure out what the URL needs to be.
    %

  • Create a simple connection with mysql

    hello
    my name is edvanio i am from brazil.
    i'd like to connect one program in Java with mysql for insert, delete and update one simple base ex. teste with nome and fone.
    thank , bye

    here's a couple of sites
    http://www.javacoding.net/articles/technical/java-mysql.html
    http://www.developer.com/java/data/article.php/3417381
    I recently installed MySQL (just to see if I could get a working program to run)
    these were the steps
    1. downloaded MySQL
    2. downloaded the connector file
    3. unzipped/installed MySQL
    4. unzipped the connector file
    mysql-connector-java-3.0.17-ga-bin.jar
    copied the jar file into this directory
    C:\Program Files\Java\jdk1.5.0_03\jre\lib\ext
    5. opened MySQL, using the code from Gamelan
    create the db JunkDB
    created the user, permissions, password
    6. combined the code from both sites (code follows)
    and it worked OK
    import java.sql.*;
    class MySQL_Test
      public MySQL_Test() throws Exception
        testDriver();
        Connection con = getConnection();
        executeUpdate(con,"CREATE TABLE test(id int,text varchar(20))");
        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')");
        executeQuery(con,"select * from test");
        executeUpdate(con,"drop table test");
        con.close();
      protected void testDriver() throws Exception
        try
          Class.forName("com.mysql.jdbc.Driver");
          System.out.println("MySQL Driver found");
        catch(ClassNotFoundException cnfe)
          System.out.println("OOPs - MySQL Driver nowhere to be found");
          throw (cnfe);
      protected Connection getConnection() throws Exception
        String url = "";
        try
          url = "jdbc:mysql://localhost:3306/JunkDB";
          Connection con = DriverManager.getConnection(url,"auser","drowssap");
          System.out.println("Connection OK");
          return con;
        catch(SQLException sqle)
          System.out.println("OOPs - No Connection");
          throw (sqle);
      protected void executeUpdate(Connection con,String sqlStatement) throws Exception
        try
          Statement s = con.createStatement();
          s.execute(sqlStatement);
          s.close();
        catch(SQLException sqle)
          System.out.println("OOPs - error executing statement");
          throw (sqle);
      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 sqle)
          System.out.println("OOPs - error executing resultset");
          throw (sqle);
      public static void main(String[] args)
        try
          new MySQL_Test();
        catch(Exception e){e.printStackTrace();}
    }

  • [JAVA] problems with java and mysql

    Hi, i have already installed php + mysql and work's them fine, but i want to install java + mysql. I have downloaded eclipse and installed its, that's ok. I have download tomcat and, that's ok. I have download module jconnector and have copied the file .jar in the java home and set classpath. Run and compiled this source that's ok. At runtime the program ask: Impossible connection at the database, why ? It's the source of program:
    [JAVA]
    import java.sql.*;
    public class connessione {
    private String nomeDB; // Nome del Database a cui connettersi
    private String nomeUtente; // Nome utente utilizzato per la connessione al Database
    private String pwdUtente; // Password usata per la connessione al Database
    private String errore; // Raccoglie informazioni riguardo l'ultima eccezione sollevata
    private Connection db; // La connessione col Database
    private boolean connesso; // Flag che indica se la connessione � attiva o meno
    public connessione(String nomeDB) { this(nomeDB, "", ""); }
    public connessione(String nomeDB, String nomeUtente, String pwdUtente) {
    this.nomeDB = nomeDB;
    this.nomeUtente = nomeUtente;
    this.pwdUtente = pwdUtente;
    connesso = false;
    errore = "";
    // Apre la connessione con il Database
    public boolean connetti() {
    connesso = false;
    try {
    // Carico il driver JDBC per la connessione con il database MySQL
    Class.forName("com.mysql.jdbc.Driver");
    // Controllo che il nome del Database non sia nulla
    if (!nomeDB.equals("")) {
    // Controllo se il nome utente va usato o meno per la connessione
    if (nomeUtente.equals("")) {
    // La connessione non richiede nome utente e password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB);
    } else {
    // La connessione richiede nome utente, controllo se necessita anche della password
    if (pwdUtente.equals("")) {
    // La connessione non necessita di password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB + "?user=" + nomeUtente);
    } else {
    // La connessione necessita della password
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB + "?user=" + nomeUtente + "&password=" + pwdUtente);
    // La connessione � avvenuta con successo
    connesso = true;
    } else {
    System.out.println("Manca il nome del database!!");
    System.out.println("Scrivere il nome del database da utilizzare all'interno del file \"config.xml\"");
    System.exit(0);
    } catch (Exception e) { errore = e.getMessage(); }
    return connesso;
    public static void main(String [] args) {
    connessione a=new connessione("asta","root","");
    if(a.connetti())
    System.out.println("Connessione al database riuscita");
    else
    System.out.println("Connessione al database non riuscita");
    [JAVA]

    With this line I always pass the username and password also:
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB);
    db = DriverManager.getConnection("jdbc:mysql://localhost/" + nomeDB, useName, Password);
    Make sure you create your users in MySQL with the correct permissions

Maybe you are looking for

  • Error while applying the patch 9909156

    while applying patch 9909156. I am getting jsp compilation errors in the patch log [1634474] !!COMPILATION ERROR(0) ibeCRgpPartnerPriCreate.jsp: this is similar MOS doc 579439.1 - Application Of Patch 5720979 Results In COMPILATION ERROR(0) ibeCOtdOr

  • Error message when opening Firefox and loading very slow:

    This is the error message I am getting everytime I try to open Firefox - either from the shortcut or from a program such as Outlook: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [ISkypeFfExtension.Initialize]" nsresul

  • Servlet filter in JSP

    hi all, i am working with session and jsp, for session authentication i m using servlet filter , which work fine in IE but when i run it in WAP emulator it give null exception. i m using xhtml which run both in IE and WAP EMulator. i dont know y it i

  • Pourquoi itunes match se déconnecte t'il aussi fréquemment ?

    Bonjour, Je suis abonné à itunes match, ce qui est très pratique pour synchroniser tout mes appareils. En revanche itunes match se déconnecte très frequemment sur mon ordinateur sous windows 7 (quasiment tous les jours), ce qui m'oblige à me déconnec

  • PTUPGCONVERT

    PTUPGCONVERT is running slow for my PT848 to 852 Tools Upgrade . The name of the step is "Running PeopleTools COnversion" What can be done to see its logs and make it fast? ---Finally it finished but it took 1 hr 48 minutes. Do you think if i do dire