如何使用java连接到mysql?

时间:2012-02-01 19:57:00

标签: java mysql

我想将Gmail中的电子邮件存储到我的mysql数据库中。 我发现有谷歌的Inboxreader,但连接到mysql的部分无法正常工作。 用户名,数据库名称,密码是否正确。

任何人都可以帮助我。 谢谢。

这是代码的一部分

{
            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

以下是错误代码:

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)

谢谢

4 个答案:

答案 0 :(得分:7)

这是你的问题:

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

您在null中获得url值。那是因为您的属性文件中没有名为jdbc:mysql://localhost/test的属性。

您有两种选择。一个人会直接使用url,例如:

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

另一个选项是在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

答案 1 :(得分:2)

您正试图从details获取属性的值,如下所示:

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

在我看来,物业的名称实际上是你的价值。

答案 2 :(得分:2)

这是因为您的属性文件中没有一个键“jdbc:mysql:// localhost / test”。假设details.properties有这样的内容:

url=jdbc:mysql://localhost/test

所以你的代码应该是

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

答案 3 :(得分:0)

我很清楚你的属性键是坏的:  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