Sergey Scopin Sergey Scopin - 1 month ago 19
MySQL Question

Java+MySQL with JDBC connector mistake

I'm trying to connect Java and MySQL with JDBC connector. So, I've downloaded connector from official cite, added it to classpath and added to the libraries of eclipse.
Now i'm using the code below

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
}
}
}


But in string: ResultSet rs = stmt.execute(query); there is a mistake "Type mismatch: cannot convert from boolean to ResultSet".
I can't understand what the problem is. Need some help.

Answer

The Statement#execute method returns a boolean. You are looking for the Statement#executeQuery method, which returns a ResultSet.

Your code should be like this:

ResultSet rs = stmt.executeQuery(query);