spring 整合jdbc(一)

来源:互联网 发布:青果软件 编辑:程序博客网 时间:2024/06/05 03:56

没有使用spring注入时   我们需要采用的方法就是利用dataSource进行与数据库的连接:

DriverManagerDataSource dataSource=new DriverManagerDataSource();dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mysql");dataSource.setUser("root");dataSource.setPassword("chen");Connection connection=null;Statement statement=null;ResultSet rs=null;try {connection=dataSource.getConnection();statement=(Statement) connection.createStatement();rs=statement.executeQuery("select * from student");


这里是采用了spring注入后  我们建里的bean是dataSource,就不用在实例化 DriverManagerDataSource  ,这是spring反向注入的好处之一:

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");DataSource dataSource=(DataSource) ctx.getBean("dataSource");Connection connection=null;Statement statement=null;ResultSet rs=null;try {connection=dataSource.getConnection();statement=(Statement) connection.createStatement();rs=statement.executeQuery("select * from student");while (rs.next()) {System.out.print("编号="+rs.getInt(1));System.out.print("用户名="+rs.getString("username"));System.out.print("密码="+rs.getString("password"));System.out.println("年龄="+rs.getString("age"));}

 

Statement 是 Java 执行数据库操作的一个重要方法,用于在已经建立数据库连接的基础上,向数据库发送要执行的SQL语句。

Statement对象,用于执行不带参数的简单SQL语句。

Statement 对象用于将 SQL 语句发送到数据库中。实际上有三种 Statement 对象,它们都作为在给定连接上执行 SQL 语句的包容器:Statement、PreparedStatement(它从 Statement 继承而来)和 CallableStatement(它从 PreparedStatement 继承而来)。它们都专用于发送特定类型的 SQL 语句: Statement 对象用于执行不带参数的简单 SQL 语句;PreparedStatement 对象用于执行带或不带 IN 参数的预编译 SQL 语句;CallableStatement 对象用于执行对数据库已存在的存储过程的调用

在spring的配置文件中利用向导添加dataSource的bean时系统会自动给你加入Myeclipes中dataSource的类库<bean id="dataSource"
  class="org.apache.commons.dbcp.BasicDataSource">报错:java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool

上网查过后的原因是:工程中少了org/apache/commons/pool/impl/GenericObjectPool 所在的包: 这个 类在commons-pool.jar包中 请去apache官方下载一个,放到工程中。

所以这里要改为:<bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">,它是通过DriverManagerDataSource类中的DriverManager来进行驱动

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


 

原创粉丝点击