如何使用java连接到mysql?
我想将Gmail中的电子邮件存储到我的mysql数据库中。 我发现Inboxreader与谷歌,但部分连接到MySQL是行不通的。 用户名,数据库名称,密码是否正确。如何使用java连接到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)
谢谢
这是你的问题:
String url = details.getProperty("jdbc:mysql://localhost/test");
你正在获得在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
你试图从details
像THI得到一个属性的值s:
String url = details.getProperty("jdbc:mysql://localhost/test");
在我看来,那里的财产的名称实际上是你的价值。
非常感谢帕布罗先生,塞尔吉奥和fivedigit – Pacific 2012-02-01 20:13:03
那是因为您的属性文件中没有一个键“jdbc:mysql:// localhost/test”。比方说,details.properties有这样的内容:
url=jdbc:mysql://localhost/test
所以,你的代码应该是
String url = details.getProperty("url");
我敢prety确保您的属性键不好: 字符串URL = details.getProperty(” JDBC:MySQL的://本地主机/测试“);
,如果你有正确的密钥
如果(details.getProperty( “JDBC:MySQL的://本地主机/测试”,你可以使用验证)!=空|| details.getProperty(“JDBC:MySQL的:// localhost/test“).trim()。length> 0){ url = details。的getProperty( “JDBC:MySQL的://本地主机/测试”); } else {
return new exception(“Wrong property key”); }
Saludos
@Pacific - 但也没有理由去配合你的Java代码到MySQL。因为你已经有'details.properties'放入类似'jdbc.url = jdbc:mysql:// etc'和'jdbc.driver = com.mysql.jdbc.Driver'的东西,那么你可以做'Class.forName(details .getProperty(“jdbc.driver”))' – 2012-02-01 20:08:04