jdbc的使用

1 什么是JDBC

  JDBC(JavaDataBase Connectivity)就是Java数据库连接,说白了就是用Java语言来操作数据库。原来我们操作数据库是在控制台使用SQL语句来操作数据库,JDBC是用Java语言向数据库发送SQL语句

2 JDBC核心类(接口)介绍

JDBC中的核心类有:DriverManager、Connection、Statement,和ResultSet


案例
JDBCUtils工具类
public class JDBCUtils {

	static Connection conn = null;
	static String url = null;
	static String username = null;
	static String password = null;
	static String driver = null;
	static {

		try {
			readConfig();
			// 注册驱动
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void readConfig() throws IOException {
		InputStream inputStream = JDBCUtils.class.getClassLoader()
				.getResourceAsStream("db.properties");
		Properties p = new Properties();
		p.load(inputStream);
		url = p.getProperty("jdbc.url");
		username = p.getProperty("jdbc.user");
		password = p.getProperty("jdbc.password");
		driver = p.getProperty("jdbc.driverClass");

	}

	public static Connection getConnection() {
		try {
			// 获取连接
			conn = DriverManager.getConnection(url, username, password);

		} catch (Exception e) {
			throw new RuntimeException("数据库连接失败");
		}
		return conn;

	}

	public static void closeResultSet(ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void closeStatement(Statement ps) {
		try {
			if (ps != null)
				ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void closeConnection(Connection conn) {
		try {
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
测试方法
public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<User> list = new ArrayList<User>();
		try {
			conn = JDBCUtils.getConnection();
			String sql = "select * from user where name=? and address=?";
			ps = conn.prepareStatement(sql);
			// 执行sql
			ps.setString(1, "zhengjun");
			ps.setString(2, "南阳");
			rs = ps.executeQuery();
			User user = null;
			while (rs.next()) {
				user = new User();
				user.setUid(rs.getInt("uid"));
				user.setName(rs.getString("name"));
				user.setAddress(rs.getString("address"));
				list.add(user);
			}

			for (User users : list) {
				System.out.println(users);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			JDBCUtils.closeResultSet(rs);
			JDBCUtils.closeStatement(ps);
			JDBCUtils.closeConnection(conn);

		}
	}




阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ZJ_2420441444/article/details/79948790
个人分类: java
上一篇MySQL的常规操作
下一篇HTTP&TOMCAT
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭