Jdbc简介
JDBC(Java Data Base Connectivity )(java 数据库连接)
可以为多种数据库提供统一的数据库访问。
JDBC使用详解
JDBC编程步骤
1. 加载驱动程序:Class.forName(driverClass)
加载Mysql驱动Class.forName(“com.mysql.jdbc.Driver”);
加载Oracle驱动:Class.forName(“oracle.jdbc.driver.OracleDriver”);
2. 获得数据库连接
DriverManager.getConnection(“jdbc:mysql://127.0.0.1:3306/imooc”,”root”,”root”);
3. 创建Statement对象:conn.createStatement();
例子:简单MVC模式数据库操作
1.首先创建我们的数据库。
- CREATE TABLE `imooc_goddess` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `user_name` varchar(30) NOT NULL,
- `sex` int(11) DEFAULT NULL,
- `age` int(11) DEFAULT NULL,
- `birthday` date DEFAULT NULL,
- `email` varchar(30) DEFAULT NULL,
- `mobile` varchar(11) DEFAULT NULL,
- `create_user` varchar(30) DEFAULT NULL,
- `create_date` date DEFAULT NULL,
- `update_user` varchar(30) DEFAULT NULL,
- `update_date` date DEFAULT NULL,
- `isdel` int(11) DEFAULT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
- /*
- * 模型层,创建类对应我们的数据库
- */
- public class Godness {
- private Integer id;
- private String user_name;
- private Integer sex;
- private Integer age;
- private Date birthday;
- private String email;
- private String mobile;
- private String create_user;
- private String update_user;
- private Date create_date;
- private Date update_date;
- private Integer isdel;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUser_name() {
- return user_name;
- }
- public void setUser_name(String user_name) {
- this.user_name = user_name;
- }
- public Integer getSex() {
- return sex;
- }
- public void setSex(Integer sex) {
- this.sex = sex;
- }
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getMobile() {
- return mobile;
- }
- public void setMobile(String mobile) {
- this.mobile = mobile;
- }
- public String getCreate_user() {
- return create_user;
- }
- public void setCreate_user(String create_user) {
- this.create_user = create_user;
- }
- public String getUpdate_user() {
- return update_user;
- }
- public void setUpdate_user(String update_user) {
- this.update_user = update_user;
- }
- public Date getCreate_date() {
- return create_date;
- }
- public void setCreate_date(Date create_date) {
- this.create_date = create_date;
- }
- public Date getUpdate_date() {
- return update_date;
- }
- public void setUpdate_date(Date update_date) {
- this.update_date = update_date;
- }
- public Integer getIsdel() {
- return isdel;
- }
- public Integer getAge() {
- return age;
- }
- public void setAge(Integer age) {
- this.age = age;
- }
- public void setIsdel(Integer isdel) {
- this.isdel = isdel;
- }
- @Override
- public String toString() {
- return "Godness [id=" + id + ", user_name=" + user_name + ", sex="
- + sex + ", age=" + age + ", birthday=" + birthday + ", email="
- + email + ", mobile=" + mobile + ", create_user=" + create_user
- + ", update_user=" + update_user + ", create_date="
- + create_date + ", update_date=" + update_date + ", isdel="
- + isdel + "]";
- }
- }
- public class DBUtil {
- private static final String URL = "jdbc:mysql://127.0.0.1:3306/jdbcdb";
- private static final String USER = "root";
- private static final String PASSWORD = "limeng";
- private static Connection conn = null;
- static {
- // 1.加载驱动程序
- try {
- Class.forName("com.mysql.jdbc.Driver");
- // 2.获得数据库连接
- conn = DriverManager.getConnection(URL, USER, PASSWORD);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static Connection getConnection() {
- return conn;
- }
- }
- //增删改查方法
- public class GodnessDao {
- public void addGodness(Godness godness) throws SQLException{
- Connection conn = DBUtil.getConnection();
- String sql = ""+
- "insert into imooc_goddess"+
- "(user_name,sex,age,birthday,email,mobile,"+
- "create_user,create_date,update_user,update_date,isdel)"+
- "values("+
- "?,?,?,?,?,?,?,current_date(),?,current_date(),?)";
- //预编译sql语句
- PreparedStatement ptmt = conn.prepareStatement(sql);
- ptmt.setString(1, godness.getUser_name());
- ptmt.setInt(2, 1);
- ptmt.setInt(3, godness.getAge());
- ptmt.setDate(4, new Date(godness.getBirthday().getTime()));
- ptmt.setString(5, godness.getEmail());
- ptmt.setString(6, godness.getMobile());
- ptmt.setString(7, godness.getCreate_user());
- ptmt.setString(8, godness.getUpdate_user());
- ptmt.setInt(9, 0);
- ptmt.execute();
- }
- public void updateGodness(Godness godness) throws SQLException{
- Connection conn = DBUtil.getConnection();
- String sql = ""+
- " update imooc_goddess"+
- " set user_name=?,sex=?,age=?,birthday=?,email=?,mobile=?,"+
- " create_user=?,update_user=?,update_date=current_date(),isdel=?"+
- " where id=?";
- //预编译sql语句
- PreparedStatement ptmt = conn.prepareStatement(sql);
- ptmt.setString(1, godness.getUser_name());
- ptmt.setInt(2, 1);
- ptmt.setInt(3, godness.getAge());
- ptmt.setDate(4, new Date(godness.getBirthday().getTime()));
- ptmt.setString(5, godness.getEmail());
- ptmt.setString(6, godness.getMobile());
- ptmt.setString(7, godness.getCreate_user());
- ptmt.setString(8, godness.getUpdate_user());
- ptmt.setInt(9, 0);
- ptmt.setInt(10, godness.getId());
- ptmt.execute();
- }
- public void delGoddness(Integer id) throws SQLException{
- Connection conn = DBUtil.getConnection();
- String sql = ""+
- " delete from imooc_goddess"+
- " where id=?";
- //预编译sql语句
- PreparedStatement ptmt = conn.prepareStatement(sql);
- ptmt.setInt(1, id);
- ptmt.execute();
- }
- //查询所有的数据
- public List<Godness> query() throws SQLException{
- Connection conn = DBUtil.getConnection();
- Statement stmt = conn.createStatement();
- ResultSet rs = stmt.executeQuery("select * from imooc_goddess");
- List<Godness> gs = new ArrayList<Godness>();
- Godness g = null;
- while (rs.next()) {
- g = new Godness();
- g.setId(rs.getInt("id"));
- g.setUser_name(rs.getString("user_name"));
- g.setAge(rs.getInt("age"));
- g.setSex(rs.getInt("sex"));
- g.setBirthday(rs.getDate("birthday"));
- g.setEmail(rs.getString("email"));
- g.setMobile(rs.getString("mobile"));
- g.setCreate_date(rs.getDate("create_date"));
- g.setCreate_user(rs.getString("create_user"));
- g.setUpdate_date(rs.getDate("update_date"));
- g.setUpdate_user(rs.getString("update_user"));
- g.setIsdel(rs.getInt("isdel"));
- gs.add(g);
- }
- return gs;
- }
- //根据姓名进行查询
- public List<Godness> query(String name,String mobile,String email) throws SQLException{
- List<Godness> result = new ArrayList<Godness>();
- Connection conn = DBUtil.getConnection();
- StringBuilder sb = new StringBuilder();
- sb.append("select * from imooc_goddess ");
- sb.append(" where user_name like ? and mobile like ? and email like ?");
- PreparedStatement ptmt = conn.prepareStatement(sb.toString());
- ptmt.setString(1, "%"+name+"%");
- ptmt.setString(2, "%"+mobile+"%");
- ptmt.setString(3, "%"+email+"%");
- ResultSet rs = ptmt.executeQuery();
- Godness g = null;
- while (rs.next()) {
- g = new Godness();
- g.setId(rs.getInt("id"));
- g.setUser_name(rs.getString("user_name"));
- g.setAge(rs.getInt("age"));
- g.setSex(rs.getInt("sex"));
- g.setBirthday(rs.getDate("birthday"));
- g.setEmail(rs.getString("email"));
- g.setMobile(rs.getString("mobile"));
- g.setCreate_date(rs.getDate("create_date"));
- g.setCreate_user(rs.getString("create_user"));
- g.setUpdate_date(rs.getDate("update_date"));
- g.setUpdate_user(rs.getString("update_user"));
- g.setIsdel(rs.getInt("isdel"));
- result.add(g);
- }
- return result;
- }
- public List<Godness> query(List<Map<String,Object >> params) throws SQLException{
- List<Godness> result = new ArrayList<Godness>();
- Connection conn = DBUtil.getConnection();
- StringBuilder sb = new StringBuilder();
- sb.append("select * from imooc_goddess where 1=1 ");
- if(params != null && params.size()>0){
- for(int i = 0; i<params.size();i++){
- Map<String, Object> map = params.get(i);
- sb.append(" and "+map.get("name")+" "+map.get("rela")+" "+map.get("value"));
- }
- }
- PreparedStatement ptmt = conn.prepareStatement(sb.toString());
- ResultSet rs = ptmt.executeQuery();
- Godness g = null;
- while (rs.next()) {
- g = new Godness();
- g.setId(rs.getInt("id"));
- g.setUser_name(rs.getString("user_name"));
- g.setAge(rs.getInt("age"));
- g.setSex(rs.getInt("sex"));
- g.setBirthday(rs.getDate("birthday"));
- g.setEmail(rs.getString("email"));
- g.setMobile(rs.getString("mobile"));
- g.setCreate_date(rs.getDate("create_date"));
- g.setCreate_user(rs.getString("create_user"));
- g.setUpdate_date(rs.getDate("update_date"));
- g.setUpdate_user(rs.getString("update_user"));
- g.setIsdel(rs.getInt("isdel"));
- result.add(g);
- }
- return result;
- }
- public Godness get(Integer id) throws SQLException{
- Connection conn = DBUtil.getConnection();
- String sql = ""+
- " select * from imooc_goddess"+
- " where id=?";
- //预编译sql语句
- PreparedStatement ptmt = conn.prepareStatement(sql);
- ptmt.setInt(1, id);
- ResultSet rs =ptmt.executeQuery();
- Godness g = new Godness();
- while(rs.next()){
- g = new Godness();
- g.setId(rs.getInt("id"));
- g.setUser_name(rs.getString("user_name"));
- g.setAge(rs.getInt("age"));
- g.setSex(rs.getInt("sex"));
- g.setBirthday(rs.getDate("birthday"));
- g.setEmail(rs.getString("email"));
- g.setMobile(rs.getString("mobile"));
- g.setCreate_date(rs.getDate("create_date"));
- g.setCreate_user(rs.getString("create_user"));
- g.setUpdate_date(rs.getDate("update_date"));
- g.setUpdate_user(rs.getString("update_user"));
- g.setIsdel(rs.getInt("isdel"));
- }
- return g;
- }
- }
- //控制层
- public class GodnessAction {
- public void add(Godness godness) throws SQLException{
- GodnessDao dao = new GodnessDao();
- dao.addGodness(godness);
- }
- public Godness get(Integer id) throws SQLException{
- GodnessDao dao = new GodnessDao();
- return dao.get(id);
- }
- public void edit(Godness godness) throws SQLException{
- GodnessDao dao = new GodnessDao();
- dao.updateGodness(godness);
- }
- public void del(Integer id) throws SQLException{
- GodnessDao dao = new GodnessDao();
- dao.delGoddness(id);
- }
- public List<Godness> query() throws SQLException{
- GodnessDao dao= new GodnessDao();
- return dao.query();
- }
- public List<Godness> query(List<Map<String,Object >> params) throws SQLException{
- GodnessDao dao = new GodnessDao();
- return dao.query(params);
- }
- }
- public class View {
- private static final String CONTEXT = "欢迎来到女神禁区:\n" + "功能列表:\n"
- + "[MAIN/M]:主菜单\n" + "[QUERY/Q]:查看全部女神的信息\n"
- + "[GET/G]:查看某位女神的详细信息\n" + "[ADD/A]:添加女神信息\n"
- + "[UPDATE/U]:更新女神信息\n" + "[DELETE/D]:删除女神信息\n"
- + "[SEARCH/S]:查询女神信息(根据姓名、手机号来查询)\n" + "[EXIT/E]:退出女神禁区\n"
- + "[BREAK/B]:退出当前功能,返回主菜单";
- private static final String OPERATION_MAIN = "MAIN";
- private static final String OPERATION_QUERY = "QUERY";
- private static final String OPERATION_GET = "GET";
- private static final String OPERATION_ADD = "ADD";
- private static final String OPERATION_UPDATE = "UPDATE";
- private static final String OPERATION_DELETE = "DELETE";
- private static final String OPERATION_SEARCH = "SEARCH";
- private static final String OPERATION_EXIT = "EXIT";
- private static final String OPERATION_BREAK = "BREAK";
- public static void main(String[] args) {
- System.out.println(CONTEXT);
- Scanner scanner = new Scanner(System.in);
- Godness godness = new Godness();
- GodnessAction action = new GodnessAction();
- String prenious = null;
- Integer step=1;
- List<Map<String, Object>> params = new ArrayList<Map<String,Object>>();
- while (scanner.hasNext()) {
- String in = scanner.next().toString();
- if (OPERATION_EXIT.equals(in.toUpperCase())
- || OPERATION_EXIT.substring(0, 1).equals(in.toUpperCase())) {
- System.out.println("你已退出");
- break;
- }else if (OPERATION_MAIN.equals(in.toUpperCase())
- || OPERATION_MAIN.substring(0, 1).equals(in.toUpperCase())
- ||OPERATION_BREAK.equals(in.toUpperCase())
- ||OPERATION_BREAK.substring(0, 1).equals(in.toUpperCase())){
- System.out.println(CONTEXT);
- }else if (OPERATION_SEARCH.equals(in.toUpperCase())
- || OPERATION_SEARCH.substring(0, 1).equals(in.toUpperCase())
- || OPERATION_SEARCH.equals(prenious)) {
- //根据姓名和电话号码查询
- prenious = OPERATION_SEARCH;
- if(step ==1){
- System.out.println("请输入女神的[姓名]");
- }else if(step ==2){
- Map<String, Object> p = new HashMap<String, Object>();
- p.put("name", "user_name");
- p.put("rela", "=");
- p.put("value","'"+in+"'");
- params.add(p);
- System.out.println("请输入女神的[电话]");
- }else if(step == 3){
- Map<String, Object> p = new HashMap<String, Object>();
- p.put("name", "mobile");
- p.put("rela", "=");
- p.put("value", "'"+in+"'");
- params.add(p);
- try {
- List<Godness> res = action.query(params);
- for(Godness g:res){
- System.out.println(g.getId() + " , " + g.getUser_name()
- + " , " + g.getSex() + "," + g.getAge() + ","
- + g.getBirthday() + "," + g.getEmail() + ","
- + g.getMobile() + "," + g.getIsdel());
- }
- step = 1;
- prenious = null;
- params.clear();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if(OPERATION_SEARCH == prenious){
- step ++;
- }
- }else if (OPERATION_UPDATE.equals(in.toUpperCase())
- || OPERATION_UPDATE.substring(0, 1).equals(in.toUpperCase())
- || OPERATION_UPDATE.equals(prenious)) {
- prenious = OPERATION_UPDATE;
- // 更新女神
- if(1==step){
- System.out.println("请输入要修改女神的[id]:");
- }else if(2==step){
- godness.setId(Integer.valueOf(in));
- System.out.println("请输入女神[姓名]");
- }else if(3 == step){
- godness.setUser_name(in);
- System.out.println("请输入女神[年龄]");
- }else if(4 == step){
- godness.setAge(Integer.valueOf(in));
- System.out.println("请输入女神[生日],格式如:yyyy-MM-dd");
- }else if(5 == step){
- SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
- Date birthday = null;
- try{
- birthday = sf.parse(in);
- godness.setBirthday(birthday);
- System.out.println("请输入女神[邮箱]");
- }catch(ParseException e){
- e.printStackTrace();
- System.out.println("你输入的格式有误,请重新输入");
- step = 3;
- }
- }else if(6 == step){
- godness.setEmail(in);
- System.out.println("请输入女神的[手机号]");
- }else if(7==step){
- godness.setMobile(in);
- try{
- action.edit(godness);
- System.out.println("更新女神成功");
- step = 1;
- prenious = null;
- }catch(Exception e){
- e.printStackTrace();
- System.out.println("更新女神失败");
- }
- }
- if(OPERATION_UPDATE.equals(prenious)){
- step++;
- }
- }else if (OPERATION_DELETE.equals(in.toUpperCase())
- || OPERATION_DELETE.substring(0, 1).equals(in.toUpperCase())
- || OPERATION_DELETE.equals(prenious)) {
- prenious = OPERATION_DELETE;
- if(step == 1){
- step ++;
- System.out.println("删除女神信息,请输入ID:");
- }else{
- try {
- action.del(Integer.valueOf(in));
- System.out.println("删除成功!");
- } catch (NumberFormatException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- step --;
- prenious = null;
- }
- }else if (OPERATION_GET.equals(in.toUpperCase())
- || OPERATION_GET.substring(0, 1).equals(in.toUpperCase())
- || OPERATION_GET.equals(prenious)) {
- prenious = OPERATION_GET;
- if(step == 1){
- step ++;
- System.out.println("获取女神的详细信息,请输入ID:");
- }else{
- try {
- Godness godness2 = action.get(Integer.valueOf(in));
- System.out.println(godness2.getId() + " , " + godness2.getUser_name()
- + " , " + godness2.getSex() + "," + godness2.getAge() + ","
- + godness2.getBirthday() + "," + godness2.getEmail() + ","
- + godness2.getMobile() + "," + godness2.getIsdel());
- } catch (NumberFormatException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- step --;
- prenious = null;
- }
- }else if (OPERATION_QUERY.equals(in.toUpperCase())
- || OPERATION_QUERY.substring(0, 1).equals(in.toUpperCase())) {
- try {
- List<Godness> list = action.query();
- for(Godness go : list){
- System.out.println(go.getId() +" --姓名:"+go.getUser_name());
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }else if (OPERATION_ADD.equals(in.toUpperCase())
- || OPERATION_ADD.substring(0, 1).equals(in.toUpperCase())
- || OPERATION_ADD.equals(prenious)) {
- prenious = OPERATION_ADD;
- // 新增女神
- if(1==step){
- System.out.println("请输入女神[姓名]");
- }else if(2 == step){
- godness.setUser_name(in);
- System.out.println("请输入女神[年龄]");
- }else if(3 == step){
- godness.setAge(Integer.valueOf(in));
- System.out.println("请输入女神[生日],格式如:yyyy-MM-dd");
- }else if(4 == step){
- SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
- Date birthday = null;
- try{
- birthday = sf.parse(in);
- godness.setBirthday(birthday);
- System.out.println("请输入女神[邮箱]");
- }catch(ParseException e){
- e.printStackTrace();
- System.out.println("你输入的格式有误,请重新输入");
- step = 3;
- }
- }else if(5 == step){
- godness.setEmail(in);
- System.out.println("请输入女神的[手机号]");
- }else if(6==step){
- godness.setMobile(in);
- try{
- action.add(godness);
- System.out.println("新增女神成功");
- step = 1;
- prenious = null;
- }catch(Exception e){
- e.printStackTrace();
- System.out.println("新增女神失败");
- }
- }
- if(OPERATION_ADD.equals(prenious)){
- step++;
- }
- } else {
- System.out.println("你输入的值为:" + in);
- }
- }
- }
- }