gpt4 book ai didi

Java+MySQL with JDBC connector错误

转载 作者:行者123 更新时间:2023-11-29 04:26:51 25 4
gpt4 key购买 nike

我正在尝试使用 JDBC 连接器连接 Java 和 MySQL。所以,我从 official cite 下载了连接器,将其添加到类路径并添加到 eclipse 的库中。现在我正在使用下面的代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


public class LocalhostDBConnection
{
LocalhostDBConnection()
{
Connection connection;
try {
// Название драйвера
String driverName = "com.mysql.jdbc.Driver";

Class.forName(driverName);

// Create a connection to the database
String serverName = "localhost";
String mydatabase = "AvtoKovriki";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "root";
String password = "";

connection = DriverManager.getConnection(url, username, password);
System.out.println("is connect to DB" + connection);

String query = "Select * FROM users";
Statement stmt = connection.createStatement();

ResultSet rs = stmt.execute(query);
String dbtime;
while (rs.next())
{
dbtime = rs.getString(1);
System.out.println(dbtime);
} // end while

connection.close();
} // end try
catch (ClassNotFoundException e)
{
e.printStackTrace();
// Could not find the database driver
} catch (SQLException e)
{
e.printStackTrace();
// Could not connect to the database
}
}
}

但在字符串中:ResultSet rs = stmt.execute(query);出现错误“类型不匹配:无法从 boolean 值转换为 ResultSet”。我不明白问题出在哪里。需要一些帮助。

最佳答案

Statement#execute方法返回一个 boolean。您正在寻找 Statement#executeQuery方法,它返回一个 ResultSet

你的代码应该是这样的:

ResultSet rs = stmt.executeQuery(query);

关于Java+MySQL with JDBC connector错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com