【问题标题】:Spring + JDBC Can't connect to databaseSpring + JDBC 无法连接数据库
【发布时间】:2015-07-22 08:11:39
【问题描述】:

我正在尝试使用 spring 框架对 mysql 数据库进行一些粗略的操作。 我添加了 maven 依赖项,这是我的 datasource.xml:

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

      <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/Rubrica?" />
        <property name="username" value="user" />
        <property name="password" value="password" />
      </bean>

      <bean id="JDBCEntryDAO" class="net.tirasa.jdbc_spring_addressbook">  
        <property name="JDBC_Spring_EntryDAO" ref="JDBC_Spring_EntryDAO" />
      </bean>       
    </beans>

当我运行应用程序时,我得到一个空指针异常(在指示的行),我无法连接到数据库,这是引发异常的方法:

    @Override
    public List<Entry> list() {
        List<Entry> res = new ArrayList<Entry>();
        String sql = "SELECT * FROM Person";

        try {
            //open connection            

            Connection conn = datasource.getConnection(); //<----NULL POINTER EXCEPTION 

            //prepare the statement
            PreparedStatement ps = conn.prepareStatement(sql);

            //execute 
            ResultSet resultSet = ps.executeQuery(sql);

            //populate entry
            while (resultSet.next()) {
                Entry entry = new Entry();
                entry.setId(resultSet.getInt("id"));
                entry.setCn(resultSet.getString("cn"));
                entry.setSn(resultSet.getString("sn"));
                entry.setPn(resultSet.getString("pn"));
                res.add(entry);
            }
            resultSet.close();
            ps.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(JDBC_Spring_EntryDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return res;
    }

【问题讨论】:

  • 数据源未正确初始化。例如。不是自动接线的。可能有很多原因。在此处发布您的应用程序上下文配置以及您如何初始化数据源
  • 你是如何注入数据源的?@Inject 私有数据源数据源?
  • @StanislavL 我使用 datasource.xml 来设置数据源,这是我发布的文件。使用这个文件是否正确?

标签: java mysql spring maven jdbc


【解决方案1】:

我认为你需要注入数据源

  <bean id="JDBCEntryDAO" class="net.tirasa.jdbc_spring_addressbook">  
    <property name="JDBC_Spring_EntryDAO" ref="JDBC_Spring_EntryDAO" />
    <property name="dataSource" ref="dataSource" />
  </bean>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-21
    • 2021-06-27
    • 2013-05-24
    • 2014-12-09
    • 1970-01-01
    • 2014-05-04
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多