gpt4 book ai didi

java - Spring + JDBC 连接不上数据库

转载 作者:行者123 更新时间:2023-11-28 23:56:24 25 4
gpt4 key购买 nike

我正在尝试使用 spring 框架在 mysql 数据库上执行一些 crud 操作。我添加了 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>

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

    @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)数据源

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

关于java - Spring + JDBC 连接不上数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31557467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com