Reputation: 2245
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.
Upvotes: 1
Views: 1887
Reputation: 1
stmt.execute(query);
returns boolean not ResultSet. You can get
ResultSet by using stmt.executeQuery()
method for queries that won't
modify data in the database.
If you want to modify data in your Database use the executeUpdate()
method, which will return an integer to indicate whether data has been modified or not.
Upvotes: 0
Reputation: 1504182
Firstly, this has nothing to do with MySQL - you're not getting as far as running the code, and none of your code deals with MySQL-specific types. (My point is that you may or may not have the MySQL jar file in the right place; this error isn't due to that.)
If you look at the documentation for Statement.execute(String)
you'll see that that returns boolean
, not ResultSet
. That's why you're getting the compile-time error.
You want executeQuery(String)
instead - or you could call execute(String)
, and if it returns true, call getResultSet
.
Upvotes: 1
Reputation: 14558
You need to use executeQuery(String sql)
method
see javadocs for more details about the provided methods
http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html
Upvotes: 0
Reputation: 85809
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);
Upvotes: 4