本文实例为大家分享了spring通过jdbc连接数据库的具体代码,供大家参考,具体内容如下
首先看下整个工程的架构目录:
需要的jar包:
一、建表
create table student( id int primary key auto_increment, name varchar(32), age int, phone varchar(32) );
二、新建与数据库对应JavaBean
package com.etoak.bean;
public class Student {
private Integer id;
private String name;
private Integer age;
private String phone;
public Student() {
super();
}
public Student(String name, Integer age, String phone) {
super();
this.name = name;
this.age = age;
this.phone = phone;
}
public Student(Integer id, String name, Integer age, String phone) {
super();
this.id = id;
this.name = name;
this.age = age;
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
三、spring的applicationContext配置文件
四、编写Dao
package com.etoak.dao;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import com.etoak.bean.Student;
public class StuDaoImpl {
private JdbcTemplate jt;
public void setJt(JdbcTemplate jt) {
this.jt = jt;
}
public boolean addStu(Student stu){
String sql = "insert into student values(null,?,?,?)";
Object[] args = {stu.getName() , stu.getAge() , stu.getPhone()};
int result = jt.update(sql , args);
// result 执行当前操作影响的数据量
return result==1;
}
public boolean delStuById(Integer id){
String sql = "delete from student where id="+id;
return jt.update(sql)==1;
}
public boolean updateStu(Student stu){
String sql = "update student set name=?,age=?,phone=? where id=?";
Object[] args = {stu.getName() , stu.getAge() , stu.getPhone() , stu.getId()};
return jt.update(sql , args)==1;
}
public Map selStuById(Integer id){
String sql = "select * from student where id="+id;
Map map = jt.queryForMap(sql);
return map;
}
// List
五、测试
package com.etoak.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.etoak.bean.Student;
import com.etoak.dao.StuDaoImpl;
public class Test {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
StuDaoImpl dao = (StuDaoImpl)ac.getBean("dao");
Student stu = new Student("sheldon",30,"111");
boolean flag = dao.addStu(stu);
System.out.println(flag);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



