当前位置:首页 » 操作系统 » spring数据库操作

spring数据库操作

发布时间: 2022-05-02 18:24:48

A. idea中spring数据库操作点击一次执行两次

你好,很高兴回答你的问题。

请先检查一下mapper.add对应的sql语句。

如果有帮助到你,请点击采纳。

B. 如何用spring 调用数据库连接使用jdbc

一 ,使用spring的jdbc
1.在myeclipse添加spring jar包,
添加Spring2.5 Core/AOP/ JDBC Library
2.在applicationContext.xml中,配置jdbc bean:

C. 如何用spring连接数据库

测试主类为:

package myspring2;

import java.sql.*;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.;

public class MySpringTest {

public static void main(String args[]) throws Exception{

ApplicationContext ctx=new ("applicationContext.xml");

DataSource dataSource=ctx.getBean("dataSource",DataSource.class);

String sql="select * from user_inf";

Connection connection=dataSource.getConnection();

Statement stm=connection.createStatement();

ResultSet rs=stm.executeQuery(sql);

while(rs.next())

{ System.out.println("用户名为:");

System.out.println(rs.getString(2));

}

}

}

第一种:使用spring自带的DriverManagerDataSource 配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<!-- 使用XML Schema的p名称空间配置 -->

<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"

p:driverClassName="com.mysql.jdbc.Driver"

p:url="jdbc:mysql://localhost:3306/test"

p:username="root"

p:password="123456" / >

<!-- 采用property的普通配置 相比之下有点麻烦,但是效果是一样的哦,-->

<!--

<bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql://localhost:3306/test" />

<property name="username" value="root" />

<property name="password" value="123456" />

</bean>

-->

</beans>

第二种:C3P0数据源。
需要使c3p0的核心jar包,我使用的是c3p0-0.9.1.jar,比较稳定,推荐使用。一般在下载hibernate的时候都会自带一个: 我在hibernate-release-4.3.0.Final\lib\optional\c3p0路径下找到的。
配置文件中如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<!-- 使用XML Schema的p名称空间配置 -->

<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"

p:driverClass="com.mysql.jdbc.Driver"

p:jdbcUrl="jdbc:mysql://localhost:3306/test"

p:user="root"

p:password="123456" >

</bean>

<!-- 采用property的普通配置 相比之下有点麻烦,但是效果是一样的哦 建议使用上面的-->

<!-- <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="driverClass" value="com.mysql.jdbc.Driver" />

<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />

<property name="user" value="root" />

<property name="password" value="123456" />

</bean>

-->

</beans>

第三种:
使用apache的dbcp插件连接数据库 需要下载的jar包:commons-dbcp.jar,commons-pool.jar,commons-collection.jar
spring的配置文件中如下:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<!-- 使用XML Schema的p名称空间配置 -->

<bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

p:driverClassName="com.mysql.jdbc.Driver"

p:url="jdbc:mysql://localhost:3306/test"

p:username="root"

p:password="123456" >

</bean>

<!-- 采用property的普通配置 相比之下有点麻烦,但是效果是一样的哦 建议使用上面的-->

<!-- <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName" value="com.mysql.jdbc.Driver" />

<property name="url" value="jdbc:mysql://localhost:3306/test" />

<property name="username" value="root" />

<property name="password" value="123456" />

</bean>

-->

</beans>

第四种:
使用hibernate数据源 需要hiberante核心jar包,我使用的hibernate1的版本是hibernate-release-4.3.0.Final
目前三大框架较流行,spring一般与hiberante做搭档,数据库连接方式写在hiberante的配置文件中,在spring管理hibernate中的配置文件
中,直接读取hibernate核心配置文件即可。在使用hibernate连接数据库的时候需要读取hibernate.cfg.xml的配置文件和相应的实体类,
读者可参照下面的自己配置一下

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="configLocations">

<list>

<value>classpath:com/config/hibernate.cfg.xml</value>

</list>

</property>

<property name="mappingLocations">

<!-- 所有的实体类映射文件 -->

<list>

<value>classpath:com/hibernate/*.hbm.xml</value>

</list>

</property>

D. 有没有大神给我讲一下springmvc操作数据库

一直用的是ssh,因为公司要用到SpringMVC,以前也没接触过,所以今天来和大家一起学习一下这个框架,以便工作需要。

例子大家可以到我上传的资源处http://download.csdn.net/download/tjcyjd/4251483下载。

首先我们先来了解一下什么是模式,模式就是解决某一类问题的方法论,把解决这类问题的解决方法归总到理论的高度,这就是模式。模式是一种指导,在一个良好的指导下,有助于开发人员完成任务。做出一个优秀的设计方案,能达到事半功倍的效果。而且会得到解决问题的最佳办法。

mvc模式起源于Smalltalk语言,mvc是Model-View-Controller的简写。mvc减弱了业务逻辑接口和数据接口之间的耦合。使用MVC模式的好处有很多,可靠性强,高重用和可适应性,较低的生命周期成本,快速的部署,可维护性强等。里面的细节在这儿就不作过多的讲解。

SpringMVC的特点:

1、清晰的角色划分,Spring在Model、View和Controller方面提供了一个非常清晰的划分,这3个方面真正是各司其职,各负其责。

2、灵活的配置功能,因为Spring的核心是IOC,同样在实现MVC上,也可以把各种类当做Bean来通过XML进行配置。

3、提供了大量的控制器接口和实现类,这样开发人员可以使用Spring提供的控制器实现类,也可以自己实现控制器接口。

4、SpringMVC是真正的View层实现无关的,它不会强制开发员使用JSP,我们可以使用其他View技术,比如Velocity,Xskt等。

5、国际化支持,Spring的ApplicationContext提供了对国际化的支持,在这里可以很方便的使用。

6、面向接口编程,其实这不仅是springMVC的特点,整个Spring来看,这个特点都是很明显的,因为它使开发人员对程序易于进行测试,并且很方便的进行管理。

7、Spring提供了Web应用开发的一整套流程,而不仅仅是MVC,他们之间可以很方便的结合在一起。下面有一个自己做得例子,做完这个例子后真的体会到了SpringMVC的强大。

下面开始配置我们的Springmvc工程:

首先我们配置WEB-INF目录下的web.xml:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5"

xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<servlet>

<!--springmvc的核心是DispatcherServlet,它负责控制整个页面的请求路径-->

<servlet-name>dispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--初始化参数>/WEB-INF/classes/相当于src目录-->

<init-param>

<!-- 这个param-name必须是contextConfigLocation-->

<param-name>contextConfigLocation</param-name>

<param-value>/WEB-INF/classes/applicationContext.xml</param-value>

</init-param>

<load-on-startup>2</load-on-startup>

</servlet>

<!--拦截所有以do结尾的请求-->

<servlet-mapping>

<servlet-name>dispatcherServlet</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

<!--处理从页面传递中文到后台而出现的中文乱码问题-->

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

</web-app>

每次配置好一个文件后建议先启动服务器看看是否产生异常,不然到后期会很难调试和找到异常所在。

WEB.XML配置好以后我们还需要在SRC目录下创建一个db-config.properties文件来存放我们的数据源配置信息:

内容如下:

db.url= jdbc:mysql:///springmvcdb?useUnicode=true&characterEncoding=utf8

db.username=root

db.password=root

db.dirverClass= com.mysql.jdbc.Driver

db-config.properties配置好以后就开始配置applicationContext.xml文件:

<?xml version="1.0"encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- 定义个缺省的控制适配器 -->

<bean

class="org.springframework.web.servlet.mvc."/>

<!-- 获取配置文件 -->

<bean id="config"

class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="locations">

<list>

<value>classpath:db-config.properties</value>

</list>

</property>

</bean>

<!-- 获取数据源 -->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName">

<value>${db.dirverClass}</value>

</property>

<property name="url">

<value>${db.url}</value>

</property>

<property name="username">

<value>${db.username}</value>

</property>

<property name="password">

<value>${db.password}</value>

</property>

</bean>

<!--

URL到处理器的映射列表可以配置多个

mappings属性健值为URL程序文件地址,而值为处理器的Bean名字,URL程序文件地址可采用路径匹配的模式,如:

com/mvc/t?st.jsp:匹配com/mvc/test.jsp、com/mvc/tast.jsp等 com/mvc /*.jsp

:匹配所有com/mvc/下带jsp后缀的URL com/mvc

/**/test.jsp:匹配所有在com/mvc路径下或子孙路径下的test.jsp com/mvc

/**/*.jsp:匹配所有com/mvc路径下或子孙路径下带.jsp后缀的URL cn/**/web/bla.jsp:匹配

cn/option/web/dog.jsp cn/option/test/web/dog.jsp cn/web/dog.jsp的请求

-->

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

<property name="mappings">

<value>

user.do=userAction

</value>

</property>

</bean>

<!--定义视图通过internalResourceView来表示使用的是Servlet/jsp技术-->

<bean id="viewResolver"

class="org.springframework成都erp系统软件开发公司http://www.yingtaow.com/erp/?web.servlet.view.InternalResourceViewResolver">

<property name="viewClass">

<value>org.springframework.web.servlet.view.InternalResourceView

</value>

</property>

<!--jsp存放的目录-->

<property name="prefix">

<value>/jsp/</value>

</property>

<!--jsp文件的后缀-->

<property name="suffix">

<value>.jsp</value>

</property>

</bean>

<bean id="userDao" class="com.yjde.springmvc.UserDao">

<property name="dataSource"ref="dataSource"></property>

</bean>

<!--定义控制器-->

<bean id="userAction" class="com.yjde.springmvc.UserController">

<property name="">

<ref bean="userDao"/>

</property>

<property name="commandClass">

<value>com.yjde.springmvc.UserDao</value>

</property>

<property name="viewpage">

<value>userInfo</value>

</property>

</bean>

</beans>

ApplicationContext.xml文件配置好以后我们开始编写具体的JAVA类,我们需要一个Dao类,一个controller类和一个PO

我们在MySql中创建了一张USERMBO表,里面有三个字段 USERID,USERNAME,USERAGE

UserDao类:

package com.yjde.springmvc;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Collection;

import java.util.List;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

@SuppressWarnings("all")

public class UserDao extends JdbcDaoSupport {

private String msg;

public String getMsg() {

return msg;

}

public void setMsg(String msg) {

this.msg = msg;

}

// 此方法把USEMBO表对应的字段查询出来依次放入userPO中

public Collection<UserPO> doquery() {

String sql = "SELECT T.USERID,T.USERNAME,T.USERAGE FROM USERMBO T";

return super.getJdbcTemplate().query(sql, new RowMapper() {

public Object mapRow(ResultSet rs, int num) throws SQLException {

UserPO user = new UserPO();

user.setUserId(rs.getInt("USERID"));

user.setUserName(rs.getString("USERNAME"));

user.setUserAge(rs.getInt("USERAGE"));

return user;

}

});

}

}

JdbcTemplate是core包的核心类。它替我们完成了资源的创建以及释放工作,从而简化了我们对JDBC的使用。它还可以帮助我们避免一些常见的错误,比如忘记关闭数据库连接。具体请参阅API

Controller类:

package com.yjde.springmvc;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.SimpleFormController;

@SuppressWarnings("all")

// SimpleFormController是spring提供的表单控制器,把页面中Form中的元素名称设定为和bean中的一样,当传入的时候Spring会自动抓取form中和Bean名称一样的元素值,把它转换成一个bean,使得开发人员可以很方便的使用。

public class UserController extends SimpleFormController {

private String viewpage;

private UserDao ;

public String getViewpage() {

return viewpage;

}

public void setViewpage(String viewpage) {

this.viewpage = viewpage;

}

@Override

protected ModelAndView onSubmit(HttpServletRequest request,

HttpServletResponse response, Object command, BindException errors)

throws Exception {

UserDao tmp = (UserDao) command;

Collection<UserPO> list = .doquery();

List<UserPO> users = new ArrayList<UserPO>();

UserPO user;

for (UserPO userPO : list) {

user = new UserPO();

user.setUserId(userPO.getUserId());

user.setUserName(userPO.getUserName());

user.setUserAge(userPO.getUserAge());

users.add(user);

}

Map mp = new HashMap();

mp.put("list", users);

return new ModelAndView(getViewpage(), mp);

}

public void setDao(UserDao ) {

this. = ;

}

}

UserPO类:

package com.yjde.springmvc;

public class UserPO {

private Integer userId;

private String userName;

private Integer userAge;

public Integer getUserId() {

return userId;

}

public void setUserId(Integer userId) {

this.userId = userId;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public Integer getUserAge() {

return userAge;

}

public void setUserAge(Integer userAge) {

this.userAge = userAge;

}

}

类创建完成以后我们编写两个JSP进行测试:

Index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

<form action="user.do" method="post">

请输入<input name="msg" type="text" />

<input type="submit" value="提交">

</form>

</body>

</html>

E. spring的数据库操作有用吗

spring中提供了 一个spring-jdbc,就是对jdbc的使用简化和扩展,增加一些开发效率。如果要了解更详细,可以搜索spring-jdbc使用详情。

具体spring-jdbc使用前,要导入相应的jar包,在applicationContext.xml中配置dataSource和jdbcTemplate就可以使用它了。

添删查改操作:

publicvoidadd(Useruser){
jdbcTemplate.update("INSERTINTOUSERVALUES('"
+user.getId()+"','"
+user.getName()+"','"
+user.getSex()+"','"
+user.getAge()+"')");
}

publicvoidedit(Useruser){
jdbcTemplate.update("UPDATEUSERSETname=?WHEREuser_id=?",newObject[]{name,id});
}

publicintqueryCount(){
intcount=jdbcTemplate.queryForInt("SELECTCOUNT(*)FROMUSER");
}

F. Spring连接数据库的几种常用方法

数据库是按照数据结构来组织、存储和管理数据的仓库,它产生于距今六十多年前,随着信息技术和市场的发展,特别是二十世纪九十年代以后,数据管理不再仅仅是存储和管理数据,而转变成用户所需要的各种数据管理的方式。数据库有很多种类型,从最简单的存储有各种数据的表格到能够进行海量数据存储的大型数据库系统都在各个方面得到了广泛的应用。在信息化社会,充分有效地管理和利用各类信息资源,是进行科学研究和决策管理的前提条件。数据库技术是管理信息系统、办公自动化系统、决策支持系统等各类信息系统的核心部分,是进行科学研究和决策管理的重要技术手段。数据库是一个单位或是一个应用领域的通用数据处理系统,它存储的是属于企业和事业部门、团体和个人的有关数据的集合。数据库中的数据是从全局观点出发建立的,按一定的数据模型进行组织、描述和存储。其结构基于数据间的自然联系,从而可提供一切必要的存取路径,且数据不再针对某一应用,而是面向全组织,具有整体的结构化特征。数据库中的数据是为众多用户所共享其信息而建立的,已经摆脱了具体程序的限制和制约。不同的用户可以按各自的用法使用数据库中的数据;多个用户可以同时共享数据库中的数据资源,即不同的用户可以同时存取数据库中的同一个数据。数据共享性不仅满足了各用户对信息内容的要求,同时也满足了各用户之间信息通信的要求。

G. spring mvc怎么实现数据库操作

首先,你的确定数据的主键是否可以使用序列自增。
如果可以那么你可以在插入数据的时候获取序列里的值,这样数据就不会重复了。
其次,可以创建一个公共方法,进行数据的插入操作,并且方法类型声明为 static synchronized
类型,这样基本上就不会出现数据重复的现象了
最后,要看你是怎么获得待插入源数据了,这个获得数据源的方法也做成static synchronized的公
共方法。

H. spring的数据库操作问题

spring有自己一套Orm,楼上说得不对,spring 引入jdbc的架包和org.springframework.jdbc-3.1.1.RELEASE.jar配置连接池,就可以连接数据库了,目前数据库是关系型数据库 ORM 主要是把数据库中的关系数据映射称为程序中的对象,spring当然可以了jdbcTemplate就可以实现,或者反射机制+jdbc就可以实现,没有那么复杂,如下代码是我刚刚写的楼主可以直接拿去用

首先构建User模型.应该和数据库字段相对应.数据库结构如下:
User模型:

package com.test.reflection;

public class User {
private Integer id;
private String firstname;
private String lastname;
private Integer age;

// 约定的默认构造器(必须)
public User() {

}

@Override
public String toString() {
return "id: " + this.id + " firstname: " + this.firstname
+ " lastname: " + this.lastname + " age: " + this.age;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

public String getLastname() {
return lastname;
}

public void setLastname(String lastname) {
this.lastname = lastname;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

}

然后是上次提供的DBUtils:

package com.test.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public final class DBUtils {
private static String url = "jdbc:mysql://localhost:3306/mytest";
private static String user = "root";
private static String password = "root";

// 获得连接
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(url, user, password);
}

// 释放连接
public static void free(ResultSet rs, PreparedStatement ps, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {

try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}

}

}

}

// 加载驱动
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("驱动加载出错");
}
}

}

最后最主要的ORMExample:

package com.test.reflection;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

import com.test.jdbc.DBUtils;

public class ORMExample {

public static void main(String[] args) {
User user = (User) getObject(
"select id, firstname, lastname, age from users where id = 1",
User.class);
System.out.println(user);

}

public static <T>T getObject(String sql, Class<T> clazz) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;

try {
conn = DBUtils.getConn();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
// 必须有无参的构造函数
T obj = null;
// 获得共有方法
Method[] ms = clazz.getMethods();
// 通过结果集元数据获得列数
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

if (rs.next()) {
obj = clazz.newInstance();
for (int i = 1; i <= columnCount; i++) {
String colName = rsmd.getColumnLabel(i);
String methodName = "set"
+ colName.substring(0, 1).toUpperCase()
+ colName.substring(1);
// 循环读取所有方法
for (Method m : ms) {
// 列名和set方法名如果相同则调用该方法
if (methodName.equals(m.getName())) {
m.invoke(obj, rs.getObject(colName));
}
}
}
}
return obj;
} catch (Exception e) {
throw new RuntimeException();
} finally {
DBUtils.free(rs, ps, conn);
}
}
}

热点内容
数模编程 发布:2024-10-06 04:04:43 浏览:14
雷霆一击服务器搭建 发布:2024-10-06 03:58:14 浏览:498
导演脚本 发布:2024-10-06 03:37:34 浏览:564
施耐德有密码程序如何打开 发布:2024-10-06 03:37:00 浏览:891
解压缩文件修复 发布:2024-10-06 03:31:17 浏览:703
如何设置休眠时不需要开机密码 发布:2024-10-06 03:03:25 浏览:231
密码工作三个事关的内容是什么 发布:2024-10-06 02:39:44 浏览:424
21款昂科威哪个配置好 发布:2024-10-06 02:20:39 浏览:836
拆装空调压缩机 发布:2024-10-06 01:59:47 浏览:420
dl算法 发布:2024-10-06 01:59:44 浏览:846