MySQL數據庫的增刪改查JDBC連接實現!

數據查詢:


/**
	 * 登錄/查詢
	 * 
	 * @param user
	 * @param password
	 * @throws ClassNotFoundException
	 */
	public static void login(String user, String password) {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			// 1、加載驅動//6.0以下數據庫需要加載
			// Class.forName("com.mysql.jdbc.Driver");

			// 2、建立連接
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?serverTimezone=GMT&useSSL=false",
					"root", "root");

			// 3、操作數據庫
			// 1)預編譯SQL格式
			String sql = "SELECT * FROM student WHERE name=? AND password=?";
			statement = connection.prepareStatement(sql);
			// 2)給SQL中的佔位符設置值
			statement.setString(1, user); // 給語句中的第一個問號設置值
			statement.setString(2, password); // 給語句中的第二個問號設置值
			// 3)執行查詢
			resultSet = statement.executeQuery();
			// 4)從resultset中獲取結果
			if (resultSet.next()) {
				System.out.println("登錄成功,當前登錄用戶:" + user + ",性別:" + resultSet.getString("sex"));
			} else {
				System.out.println("登錄失敗,用戶名或密碼錯誤!");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			// 4、關閉連接
			try {
				if (resultSet != null) {
					resultSet.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (statement != null) {
					statement.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}


數據新增:

Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		// 連接數據庫
		try {
			connection = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/server?serverTimezone=GMT&useSSL=false", "root", "root");
			// 新增數據的sql語句
			String sql = "insert into user values(?,?,?,?) ";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, username);
			preparedStatement.setString(2, password);
			preparedStatement.setString(3, name);
			preparedStatement.setInt(4, age);
			preparedStatement.executeUpdate();
		//關閉連接沒有寫
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


數據修改

  // // 操作數據庫
        // String sql = "UPDATE student SET sex=? WHERE name=?";
        // PreparedStatement statement = connection.prepareStatement(sql);
        // statement.setString(1, "男");
        // statement.setString(2, "李四");
        // statement.executeUpdate();
        // System.out.println("修改成功!");
        //
        // // 關閉連接
        // statement.close();
        // connection.close();

數據刪除:

// PreparedStatement preparedStatement = connection.prepareStatement("DELETE FROM student WHERE id=2");
        // preparedStatement.executeUpdate();
        // System.out.println("刪除成功!");
        //
        // // 關閉連接
        // preparedStatement.close();
        // connection.close();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章