发表于: 2017-07-30 23:32:10
3 1011
今天完成:
数据库:
创建了表customer,但是表中还没有插入元素,希望通过Spring+jdbc进行添加数据
package com.jinhege.customer.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.jinhege.customer.D.CustomerDAO;
import com.jinhege.customer.model.Customer;
public class JdbcCustomerDao implements CustomerDAO
{
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(Customer customer) {
String sql = "INSERT INTO CUSTOMER" + "(CUST_ID,NAME,AGE)VALUES(?,?,?)";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, customer.getCustId());
ps.setString(2, customer.getName());
ps.setInt(3, customer.getAge());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
public Customer findByCustomerId(int custId) {
String sql = "SELECT *FROM CUSTOMER WHERE CUST_ID = ?";
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, custId);
Customer customer = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) customer = new Customer(
rs.getInt("CUST_ID"),
rs.getString("NAME"),
rs.getInt("Age")
);
rs.close();
ps.close();
return customer;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
}
package com.jinhege.common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.jinhege.customer.D.CustomerDAO;
import com.jinhege.customer.model.Customer;
public class App {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext context =
new ClassPathXmlApplicationContext("application.xml");
CustomerDAO customerDAO = (CustomerDAO) context.getBean("customerDAO");
Customer customer = new Customer(1, "jinhege",22);
customerDAO.insert(customer);
Customer customer1 = customerDAO.findByCustomerId(1);
System.out.println(customer1);
}
}
Exception in thread "main" java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'name' cannot be null
at com.jinhege.customer.dao.impl.JdbcCustomerDao.insert(JdbcCustomerDao.java:31)
应该是元素没有通过插入成功
在DOS里插入数据:
Exception in thread "main" java.lang.RuntimeException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '0' for key 'PRIMARY'
at com.jinhege.customer.dao.impl.JdbcCustomerDao.insert(JdbcCustomerDao.java:31)
at com.jinhege.common.App.main(App.java:16)
还是数据插入读取部分有问题,明天再看看吧,今天白天停电了,所以没有多少时间。。。
明日计划:
继续改,调通程序
问题:
收获:
评论