线程“主”java.lang.Error 中的异常: Unresolved 编译问题: 类型不匹配:无法从 java.sql.Statement 转换为 com.mysql.jdbc.Statement
i am a beginner in java i am trying to use mysql database i have downloaded mysql-connector-java-5.1.23-bin.jar file from mysql.com and i have added this jar file to in my build path of my project but there is an error in the following code Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
package com.example.demo;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try
{
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}
最佳答案
错误的类
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
应该是
import java.sql.Connection;
import java.sql.Statement;
事实上,java将一切都与特定的数据库引擎解耦了。永远不需要导入 MySQL(或 ProgressSQL 或...)类。
为了让这些类在运行时可用,在 try
之后,在获得连接之前的第一件事是:
Class.forName("com.mysql.jdbc.Driver");
这种技术将允许从配置文件中读取所有字符串,并编写与数据库无关的代码。
缺少:conn = ...
conn = DriverManager.getConnection(CONN_STR, userName, userpwd);
关于java - Mysql数据库异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14988513/