使用Spring连接数据库数据创建JSON数据 作为接口

来源:互联网 发布:淘宝助理怎么使用5.5 编辑:程序博客网 时间:2024/05/16 18:56

这个是Spring的bean文件配置,配置数据库的入口,我用的是mysql。

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:lang="http://www.springframework.org/schema/lang"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd           http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">    <bean name="da"  class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="com.mysql.jdbc.Driver" />        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/lddy"></property>       /*lddy是我的数据库名称 */        <property name="user" value="root"></property>        <property name="password" value="123456"></property>    </bean></beans>



下面是代码部分。


public static void main(String[] args) throws Exception {        // TODO Auto-generated method stub        ApplicationContext ct = new ClassPathXmlApplicationContext("jdbc.xml");        DataSource da = ct.getBean("da", DataSource.class);  //获取bean的数据        Connection con = da.getConnection();   //开放连接        Statement st = con.createStatement();   // Statement用于发送不带参数的接口        String sql = "select * from test";           ResultSet rs = st.executeQuery(sql);            javabean j = new javabean();     //  一个类        JSONObject jsonbo = new JSONObject();        JSONArray jsonay = new JSONArray();        while (rs.next()) {            j.setAdd(rs.getString("url"));        //rs.getString 括号里面可以直接使用你数据库的字段名称  也可以使用下标查询            j.setName(rs.getString("name"));            j.setId(rs.getInt("id"));            j.setTel(rs.getString("telete"));            j.setText(rs.getString("text"));            jsonay.add(j);             }        System.out.println(jsonay);    }}

package com.java.bean;public class javabean {private int id;private String name;private String tel;private String text;private String add;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}public String getText() {return text;}public void setText(String text) {this.text = text;}public String getAdd() {return add;}public void setAdd(String add) {this.add = add;}}


阅读全文
1 0
原创粉丝点击