Java DB

将mysql jar包引入项目

jdbc:mysql://127.0.0.1:3306/java

java 数据库名称

 

 

package com.imooc.db;

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

public class DBUtil {

    private static final String URL = "jdbc:mysql://127.0.0.1:3306/java?useUnicode=true&characterEncoding=utf-8";
    private static final String USER = "root";
    private static final String PASSWORD = "";

    private static Connection conn = null;

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        return conn;
    }

}

 

DAO

//占位符 ? PreparedStatement 对象

package com.imooc.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.imooc.db.DBUtil;
import com.imooc.model.Goddess;

public class GoddessDao {

    public void addGoddess(Goddess g) throws Exception {

        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(),?)";

        PreparedStatement ptmt = conn.prepareStatement(sql);
        ptmt.setString(1, g.getUser_name());
        ptmt.setInt(2, g.getSex());
        ptmt.setInt(3, g.getAge());
        ptmt.setDate(4, new Date(g.getBirthday().getTime()));
        ptmt.setString(5, g.getEmail());
        ptmt.setString(6, g.getMobile());
        ptmt.setString(7, g.getCreate_user());
        ptmt.setString(8, g.getUpdate_user());
        ptmt.setInt(9, g.getIsdel());

        ptmt.execute();
    }

}

posted @ 2016-03-21 00:16  Curitis  阅读(940)  评论(0编辑  收藏  举报