jdbc_普通的连接数据库的方法

一、导入connection的jar包

jar包地址:https://pan.baidu.com/s/1L061j1ZisX-ilmc_p21vwA

二、编写代码

public static void main(String[] args) {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;

		try {
			// 1.注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			// 2.获得连接
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mytest", "root", "000000");
			// 3.创建sql语句
			String sql = "SELECT * FROM test";
			// 4.传递sql语句
			pstmt = conn.prepareStatement(sql);
			// 5.获得结果集
			rs = pstmt.executeQuery();
			// 6.打印结果集
			while (rs.next()) {
				String name = rs.getString(1);
				System.out.println(name);
			}

		} catch (ClassNotFoundException e) {
			System.out.println("连接失败");
		} catch (SQLException e) {
			System.out.println("连接失败");
		} finally {
			//7.首先判断驱动是否为空,然后关闭所有驱动
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			if (pstmt != null) {
				try {
					pstmt.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

 

 

发布了20 篇原创文章 · 获赞 13 · 访问量 9531

猜你喜欢

转载自blog.csdn.net/qq_35653657/article/details/81739078