我想知道如何连接到Xampp MySQL中托管的数据库。
到目前为止,这就是我的java代码中要连接的内容,但我不确定自己在做什么。
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection( host, username, password );
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "root";
String uPass= "password";
}
catch ( SQLException err ) {
System.out.println( err.getMessage( ) );
}
}我已经通过phpMyAdmin设置了一个数据库和表。只是不知道怎么继续。
我使用Netbeans编写代码,以连接到通过Xampp PHPMyAdmin创建的本地数据库。
最后,我想用Java创建一个数据库连接,并调用IDE中的表。会很感激你的帮助。
发布于 2014-01-26 09:52:30
这是项目的结构。

试试这个
更新
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/testspring","root", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}对我来说很管用
我从Java2s.com下载了jar
请参阅
发布于 2014-01-26 10:55:16
这是一个代码(Java 7风格,尝试-使用-资源,更简洁的风格)从您的数据库连接和检索数据。
public static final String SELECT_QUERY = "SELECT * FROM your_table_name";
public static void main(String[] args) {
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "root";
String uPass = "password";
try (Connection conn = DriverManager.getConnection(host, uName, uPass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SELECT_QUERY)) {
while (rs.next()) {
//read your lines one ofter one
int id = rs.getInt("id");
String somePropertyValue = rs.getInt("some_column_name");
// etc.
}
} catch (SQLException e) {
e.printStackTrace();
}
}此外,如果从命令行运行,则在类路径中添加JDBC驱动程序(*.jar文件),如果您正在使用IDE (Eclipse,IDEA等),则将此jar添加到您的项目中。
顺便说一句,如果变量声明在使用之后,您的代码是如何编译的?这段代码甚至不能编译。
发布于 2014-01-26 09:34:25
也许您应该在使用字符串之前定义它们。
主机URL看起来不错。
您必须在服务器中安装驱动程序,或者将其放在项目的/lib文件夹中。您可以在%DERBY_HOME%/lib文件夹(名为derby.jar )中找到它,假设%DERBY_HOME%是Derby的目录安装。
https://stackoverflow.com/questions/21361781
复制相似问题