Mysql—JDBC总结

JDBC的基本步骤

  1. 初始化一个DataSource
  2. 通过DataSource获取Connection
  3. 不停得循环执行sql
    1.通过Connection获取PrepareStatement
    2.通过setXXX系列操作填充PrepareStatement中的占位符
    3.根据有没有结果分别执行executeQurey或者executeUpdate
    4.通过ResultSet获取结果信息
    5.关闭所有资源(建议使用try—with—resource)
  4. 关闭连接(建议使用try—with—resource)
//通过DataSource获取Connection
public class DBUtil {
    private static  DataSource dataSource = null;
    public static void initDataSource() {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setServerName("127.0.0.1");
        mysqlDataSource.setPort(3306);
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("bnn19961006");
        mysqlDataSource.setDatabaseName("boke");
        mysqlDataSource.setUseSSL(false);
        mysqlDataSource.setCharacterEncoding("utf8");
        dataSource = mysqlDataSource;
    }
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();

    }
}
//连接后实现博客系统的发表文章功能
if(User.isLoginned()) {
            Scanner scan = new Scanner(System.in);
            System.out.print("请输入文章标题> ");
            String title = scan.nextLine();
            System.out.print("请输入文章内容> ");
            String content = scan.nextLine();
            int author_id = User.getCurrentUser().id;
            Date  published_at = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String publishedatstr = format.format(published_at);
            try(Connection c = DBUtil.getConnection()) {
                String sql = "insert into articles (author_id,title,content,published_at) values (?,?,?,?)";
                try(PreparedStatement s = c.prepareStatement(sql)) {
                    s.setInt(1,author_id);
                    s.setString(2,title);
                    s.setString(3,content);
                    s.setString(4,publishedatstr);
                    s.executeUpdate();
                    System.out.println("发表成功");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("您还没有登录");
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值