Mysql数据库异常 [英] Mysql database Exception

查看:70
本文介绍了Mysql数据库异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线程"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();
        }
    }
}

}

推荐答案

错误的类

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

应该是

import java.sql.Connection;
import java.sql.Statement;


实际上,java将所有内容与特定的数据库引擎分离.永远都不需要导入MySQL(或ProgressSQL或...)类.


In fact, java decouples everything from a specific database engine. One never should need an import of MySQL (or ProgressSQL or ...) classes.

要在运行时提供这些类,在获得连接之前, try 之后的第一件事是:

To have those classes available at run-time, the first thing after the try, before getting the connection would be:

Class.forName("com.mysql.jdbc.Driver");

该技术将允许从配置文件读取所有字符串,并编写独立于数据库的代码.

This technique would allow reading all strings from a configuration file, and writing database independent code.

缺少:conn = ...

Missing: conn = ...

conn = DriverManager.getConnection(CONN_STR, userName, userpwd);

这篇关于Mysql数据库异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆