Mybatis入门,从一个简单的JdbcUtil开始

这篇博客回顾了JDBC的基本使用,并预告了将通过一个简单的demo介绍Mybatis入门。作者提到在大学时期接触JDBC,而现在通过运行Java应用程序进行演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大学时候就学的最原始的JDBC,刚毕业那会,笔试还要求手写JDBC。什么都不说了,看代码吧。

首先,要去官网下载一个mysql的驱动包,如:mysql-connector-java-5.1.27.jar
然后,Run As Java Application

package com.rice.web;

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

public class JdbcUtil {

	public static void main(String[] args) {
		test();
	}

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public static Connection getMysqlConn() {
		try {
			return DriverManager.getConnection("jdbc:mysql://rm-wz9n1e39tno3o4x14do.mysql.rds.aliyuncs.com:3306/rice_dev", "rice", "abc123");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@SuppressWarnings("resource")
	public static void test() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			conn = getMysqlConn();

			ps = conn.prepareStatement("insert into t_test (name) values (?)");
			ps.setString(1, "test");
			ps.execute();

			ps = conn.prepareStatement("update t_test set name=? where id=?");
			ps.setString(1, "test1");
			ps.setInt(2, 1);
			ps.executeUpdate();

			ps = conn.prepareStatement("select id,name from t_test where id=?");
			ps.setInt(1, 1);
			rs = ps.executeQuery();
			if (rs.next()) {
				User u = new User();
				u.setId(rs.getInt(1));
				u.setName(rs.getString(2));
				System.out.println(u.toString());
			}

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

}

好了,就这么简单。


下一篇 Mybatis入门,一个简单的demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值