【问题标题】:Quick way to connect to a remote MySql Database in Java [closed]用Java连接到远程MySql数据库的快速方法[关闭]
【发布时间】:2013-05-20 18:11:04
【问题描述】:

我想从基于 Java 的框架中连接到数据库。这实质上涉及编写代码以连接到数据库。但是,我无法修改任何 build.xml 文件,例如 http://docs.oracle.com/javase/tutorial/jdbc/basics/gettingstarted.html 或下载 mysql-connector-java 等软件包。有没有办法做到这一点?

【问题讨论】:

  • 您正在编写一个框架并且您想为其开发一些连接到数据库的功能?
  • 绝对是的。我需要有 java 代码才能连接到数据库。

标签: java mysql database jdbc database-connection


【解决方案1】:

最简单的方法:

Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager
      .getConnection("jdbc:mysql://localhost/dbname?"
          + "user=myusername&password=mypassword");
PreparedStatement preparedStatement = connect
      .prepareStatement("select * from employees");
 ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
  //display text
}
preparedStatement.close();
connect.close();
    1234563另外,上面的代码假设你在数据库中有一个employees
  • 我使用了PreparedStatement 以便它进行预编译。当您有查询的参数时,它会更有用。你也可以使用 Callable 语句。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-01-29
  • 2011-12-06
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多