How to connect to mysql using java?

I want to store emails from Gmail in my mysql database. I found Inboxreader with Google, but the part for connecting to mysql does not work. username, database name, password are correct.

Can someone help me. Thank.

here is the piece of code

{
            Properties details= new Properties();
            details.load(new FileInputStream("details.properties"));
            String userName = details.getProperty("root");
            String password = details.getProperty("password");
            String url = details.getProperty("jdbc:mysql://localhost/test");
            Class.forName ("com.mysql.jdbc.Driver").newInstance ();
            conn = DriverManager.getConnection (url, userName, password);
            System.out.println ("Database connection established");
            PreparedStatement st= conn.prepareStatement("insert into 'Email_list' values(?)");
            for(String mail:mails)
            {
            try{
                  st.setString(1, mail);
                  st.execute();
                }catch(Exception e){}
            }



        }
        catch (Exception e)
        {
            System.err.println ("Cannot connect to database server");
            e.printStackTrace();
        }
        finally

Here is the error code:

Cannot connect to database server
java.sql.SQLException: The url cannot be null
Reading:23
    at java.sql.DriverManager.getConnection(DriverManager.java:554)
    at java.sql.DriverManager.getConnection(DriverManager.java:185)
    at inboxreader.InboxReader.connecttoMySql(InboxReader.java:181)
    at inboxreader.InboxReader.Start(InboxReader.java:82)
    at inboxreader.InboxReader.main(InboxReader.java:34)

thank

+5
source share
4 answers

It's your problem:

String url = details.getProperty("jdbc:mysql://localhost/test");

You get the value nullin url. This is because there is no property in your properties file jdbc:mysql://localhost/test.

You have two options. Could be used urldirectly with something like:

String url = "jdbc:mysql://localhost/test";

Another option would have a properly configured property in details.properties:

# hello, I am details.properties file
jdbc.url=jdbc:mysql://localhost/test

Java- url , :

String url = details.getProperty("jdbc.url"); // note that we're changing property name
+7

details :

String url = details.getProperty("jdbc:mysql://localhost/test");

, .

+2

, "jdbc: mysql://localhost/test" . , details.properties :

url=jdbc:mysql://localhost/test

,

String url = details.getProperty("url");
+2

, :  String url = details.getProperty( "jdbc: mysql://localhost/test" );

,

if (details.getProperty( "jdbc: mysql://localhost/test" )!= null || details.getProperty( "jdbc: mysql://localhost/test" ).trim(). length > 0 ) { url = details.getProperty( "jdbc: mysql://localhost/test" ); } {

( " " ); }

Saludos

0
source

All Articles