线程中的异常“main”java.lang.Error:未解决的编译问题: 类型不匹配:无法从java.sql.Statement转换为com.mysql.jdbc.Statement
我是java的初学者我正在尝试使用mysql数据库我从mysql.com下载了mysql-connector-java-5.1.23-bin.jar文件,我已将此jar文件添加到我的构建路径中我的项目,但以下代码中有错误 线程中的异常“main”java.lang.Error:未解决的编译问题: 类型不匹配:无法从java.sql.Statement转换为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();
}
}
}
}
答案 0 :(得分:4)
错误的课程
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);
答案 1 :(得分:0)
package com.example.demo;
import java.sql.*;
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;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
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();
}
}
}